Example usage for org.springframework.security.core Authentication getAuthorities

List of usage examples for org.springframework.security.core Authentication getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getAuthorities.

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityConnectInterceptor.java

/**
 * This callback 1)  Ensures that 2 different local users
 * cannot share the same 3rd party connection 2) Updates the current
 * user's authentication if the set of roles they are assigned
 * needs to change now that this connection has been made.
 * 3) Looks for a request previously saved by an access denied
 * handler, and if present, sets the url of this original
 * pre-authorisation request as a session attribute
 * //  w  ww . ja va  2  s  .  c  om
 */
@Override
public void postConnect(Connection<S> connection, WebRequest webRequest) {

    super.postConnect(connection, webRequest);

    /**
     * User roles are generated according to connected
     * providers in spring-social-security
     * 
     * Now that this connection has been made,
     * doe we need to update the user roles?
     * 
     * If so, update the current user's authentication and update
     * remember-me services accordingly.
     */
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    Collection<? extends GrantedAuthority> existingAuthorities = authentication.getAuthorities();

    GrantedAuthority newAuthority = userAuthoritiesService.getProviderAuthority(connection.getKey());

    if (!existingAuthorities.contains(newAuthority)) {

        Authentication newAuthentication = authenticationFactory
                .updateAuthenticationForNewConnection(authentication, connection);
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);

        if (rememberMeServices != null && webRequest instanceof ServletWebRequest) {

            ServletWebRequest servletWebRequest = ((ServletWebRequest) webRequest);
            rememberMeServices.loginSuccess(servletWebRequest.getRequest(), servletWebRequest.getResponse(),
                    newAuthentication);
        }
    }

    /**
     * This connection may have been instigated by an 
     * access denied handler which may have saved the
     * original request made by the user before their access
     * was denied.  
     * 
     * Spring Social sends the user to a particular view
     * on completion of connection.  We may wish to offer the
     * user a "continue" link on this view, allowing their
     * original request (if saved by the access denied handler)
     * to be re-attempted
     *
     */
    if (webRequest instanceof ServletWebRequest) {
        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
        SavedRequest savedRequest = requestCache.getRequest(servletWebRequest.getRequest(),
                servletWebRequest.getResponse());
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            if (redirectUrl != null && savedRequest.getMethod().equalsIgnoreCase("get")) {
                servletWebRequest.setAttribute(SAVED_REQUEST_URL_ATTRIBUTE_NAME, savedRequest.getRedirectUrl(),
                        RequestAttributes.SCOPE_SESSION);
            }
        }
    }
}

From source file:cn.com.fubon.springboot.starter.jwt.auth.JwtTokenServiceImpl.java

@Override
public String createJwtToken(Authentication authentication, int minutes) {
    Claims claims = Jwts.claims().setId(UUID.randomUUID().toString()).setSubject(authentication.getName())
            .setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000)).setIssuedAt(new Date());

    String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .map(String::toUpperCase).collect(Collectors.joining(","));

    claims.put(AUTHORITIES, authorities);

    return Jwts.builder().setClaims(claims).signWith(HS512, secretkey).compact();
}

From source file:com.creativity.security.MySimpleUrlAuthenticationSuccessHandler.java

/**
 * Builds the target URL according to the logic defined in the main class
 * Javadoc./*from  w w w .j ava 2 s  .  c  o m*/
 */
protected String determineTargetUrl(Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    boolean isAtendente = false;
    boolean isFinanceiro = false;
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("GESTOR")) {
            isUser = true;
            break;
        } else if (grantedAuthority.getAuthority().equals("ADMINISTRADOR")) {
            isAdmin = true;
            break;
        } else if (grantedAuthority.getAuthority().equals("FINANCEIRO")) {
            isFinanceiro = true;
            break;
        }
        if (grantedAuthority.getAuthority().equals("ATENDENTE")) {
            isAtendente = true;
            break;

        } else {

        }
    }

    if (isUser) {
        return "/DashboardGestor.xhtml";
    } else if (isAdmin) {
        return "/DashboardAdmin.xhtml";
    } else if (isFinanceiro) {
        return "/DashboardAdmin.xhtml";
    }
    if (isAtendente) {
        return "/DashboardAdmin.xhtml";

    } else {
        throw new IllegalStateException();
    }
}

From source file:org.exoplatform.acceptance.security.CrowdAuthenticationProviderWrapper.java

/**
 * {@inheritDoc}/* w  w  w . java 2 s . c om*/
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication crowdAuthentication = crowdAuthenticationProvider.authenticate(authentication);
    return new UsernamePasswordAuthenticationToken(crowdAuthentication.getPrincipal(),
            crowdAuthentication.getCredentials(),
            grantedAuthoritiesMapper.mapAuthorities(crowdAuthentication.getAuthorities()));
}

From source file:de.itsvs.cwtrpc.sample1.server.service.LoginServiceImpl.java

public String login(String userName, String password) throws AuthenticationException {
    final StringBuilder roleNames = new StringBuilder();
    final Authentication auth;

    auth = SecurityContextHolder.getContext().getAuthentication();
    log.info("Login of user '" + auth.getName() + "' (session ID "
            + RemoteServiceContextHolder.getContext().getServletRequest().getSession().getId() + ")");

    for (GrantedAuthority ga : auth.getAuthorities()) {
        if (roleNames.length() > 0) {
            roleNames.append(", ");
        }//from   w  ww  .  java 2s .  c  o  m
        roleNames.append(ga.getAuthority());
    }

    return roleNames.toString();
}

From source file:org.deegree.securityproxy.wcs.responsefilter.capabilities.WcsCapabilitiesModificationManagerCreator.java

public DecisionMaker createDecisionMaker(OwsRequest owsRequest, Authentication authentication) {
    checkVersion(owsRequest);//from   w  w w. j  av a 2 s. com
    List<String> blackListTextValues = new ArrayList<String>();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        addBlackListValuesFromAuthorities(blackListTextValues, grantedAuthority);
    }
    if (!blackListTextValues.isEmpty())
        return new BlackListDecisionMaker(ELEMENT_TO_FILTER, WCS_1_0_0_NS_URI, SUB_ELEMENT_NAME,
                WCS_1_0_0_NS_URI, blackListTextValues);
    return null;
}

From source file:hotel.web.util.HotelAuthenticationHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
    String userTargetUrl = "/user/index.jsp"; // change "memmber" to whatever you use
    String adminTargetUrl = "/user/index.jsp"; // change "admin" to whatever you use and add more taretURLs if needed
    Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
    if (roles.contains("ROLE_ADMIN")) {
        getRedirectStrategy().sendRedirect(request, response, adminTargetUrl);
    } else if (roles.contains("ROLE_USER")) {
        getRedirectStrategy().sendRedirect(request, response, userTargetUrl);
    } else {// ww w .  j  a v  a 2 s.  c o  m
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }
}

From source file:org.cloudfoundry.tools.security.CloudFoundryAuthenticationProviderTest.java

@Test
public void shouldAuthenticateUsingCloudFoundryLogin() throws Exception {
    setupEnvironment("user@cloudfoundry.com");
    given(this.cloudFoundryClient.login()).willReturn("token");
    this.cloudFoundryClientFactory = new CloudFoundryClientFactory() {
        @Override/*w  w w.j  a  v a  2  s  .c  o m*/
        public CloudFoundryClient getCloudFoundryClient(String username, String password,
                String cloudControllerUrl) {
            assertThat(username, is("user@cloudfoundry.com"));
            assertThat(password, is("password"));
            assertThat(cloudControllerUrl, is("https://api.cloudfoundry.com"));
            return CloudFoundryAuthenticationProviderTest.this.cloudFoundryClient;
        }
    };
    Authentication authentication = new UsernamePasswordAuthenticationToken("user@cloudfoundry.com",
            "password");
    Authentication authenticate = this.authenticationProvider.authenticate(authentication);
    verify(this.cloudFoundryClient).login();
    assertThat(authenticate, is(not(nullValue())));
    assertThat(authenticate.getAuthorities().iterator().next().getAuthority(), is("GRANTED_ROLE"));
}

From source file:org.deegree.securityproxy.wms.responsefilter.capabilities.WmsCapabilitiesModificationManagerCreator.java

private DecisionMaker createDecisionMaker(OwsRequest owsRequest, Authentication authentication) {
    checkVersion(owsRequest);//from w ww  .j ava2 s. c  o  m
    List<String> blackListLayerNames = new ArrayList<String>();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        addBlackListValuesFromAuthorities(blackListLayerNames, grantedAuthority);
    }
    return new BlackListDecisionMaker(ELEMENT_TO_FILTER, WMS_1_3_0_NS_URI, SUB_ELEMENT_NAME, WMS_1_3_0_NS_URI,
            blackListLayerNames);
}

From source file:org.appverse.web.framework.backend.api.services.presentation.impl.live.AuthenticationServiceFacadeImpl.java

@SuppressWarnings("unchecked")
@Override/*from   w w  w.  ja  v a 2 s.  c  o m*/
public List<String> getAuthorities() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    List<String> credentials = new ArrayList<String>();
    Collection<GrantedAuthority> grantedAuthorities = (Collection<GrantedAuthority>) authentication
            .getAuthorities();
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        credentials.add(grantedAuthority.getAuthority());
    }
    return credentials;
}