Search in sources :

Example 26 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project wildfly-camel by wildfly-extras.

the class DomainAuthenticationManager method authenticate.

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (!(auth instanceof UsernamePasswordAuthenticationToken))
        throw new BadCredentialsException("Unsupported authentication type: " + auth);
    LoginContextBuilder builder = new LoginContextBuilder(Type.AUTHENTICATION);
    UsernamePasswordAuthenticationToken authToken = (UsernamePasswordAuthenticationToken) auth;
    Object details = auth.getDetails();
    builder.domain(details instanceof String ? (String) details : "other");
    Object principal = authToken.getPrincipal();
    if (principal instanceof String) {
        builder.username((String) principal);
    } else {
        throw new UsernameNotFoundException("Unsupported principal: " + principal);
    }
    Object credentials = authToken.getCredentials();
    if (credentials instanceof char[]) {
        builder.password((char[]) credentials);
    } else {
        throw new BadCredentialsException("Unsupported credentials: " + credentials);
    }
    LoginContext context;
    try {
        context = builder.build();
    } catch (LoginException ex) {
        throw new AuthenticationServiceException("Cannot build login context", ex);
    }
    try {
        context.login();
    } catch (LoginException ex) {
        throw new AuthenticationServiceException("Password invalid/Password required", ex);
    }
    Collection<GrantedAuthority> authorities = new HashSet<>();
    Set<Group> groups = context.getSubject().getPrincipals(Group.class);
    if (groups != null) {
        for (Group group : groups) {
            if ("Roles".equals(group.getName())) {
                Enumeration<? extends Principal> members = group.members();
                while (members.hasMoreElements()) {
                    Principal member = members.nextElement();
                    authorities.add(new SimpleGrantedAuthority(member.getName()));
                }
            }
        }
    }
    AbstractAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    result.setDetails(details);
    return result;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Group(java.security.acl.Group) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) LoginContext(javax.security.auth.login.LoginContext) LoginException(javax.security.auth.login.LoginException) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 27 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project wildfly-camel by wildfly-extras.

the class UsernamePasswordAuthenticationAdapter method convertToAuthentication.

protected Authentication convertToAuthentication(Subject subject) {
    AbstractAuthenticationToken authToken = null;
    Set<UsernamePasswordPrincipal> principalSet = subject.getPrincipals(UsernamePasswordPrincipal.class);
    if (principalSet.size() > 0) {
        UsernamePasswordPrincipal upp = principalSet.iterator().next();
        authToken = new UsernamePasswordAuthenticationToken(upp.getName(), upp.getPassword());
    }
    if (authToken != null) {
        Set<DomainPrincipal> auxset = subject.getPrincipals(DomainPrincipal.class);
        if (auxset.size() > 0) {
            String domain = auxset.iterator().next().getName();
            authToken.setDetails(domain);
        }
    }
    return authToken;
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 28 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project incubator-atlas by apache.

the class AtlasAuthenticationFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);
                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }
                if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);
                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser, Servlets.getRequestURI(httpRequest));
                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };
    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");
        if (headerProperties != null) {
            for (String headerKey : headerProperties.stringPropertyNames()) {
                String headerValue = headerProperties.getProperty(headerKey);
                responseWrapper.setHeader(headerKey, headerValue);
            }
        }
        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        // PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(), "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) User(org.springframework.security.core.userdetails.User) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) RequestContext(org.apache.atlas.RequestContext)

Example 29 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project spring-security by spring-projects.

the class JwtAuthenticationProvider method authenticate.

/**
 * Decode and validate the
 * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer
 * Token</a>.
 * @param authentication the authentication request object.
 * @return A successful authentication
 * @throws AuthenticationException if authentication failed for some reason
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
    Jwt jwt = getJwt(bearer);
    AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
    token.setDetails(bearer.getDetails());
    this.logger.debug("Authenticated token");
    return token;
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken)

Example 30 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project spring-security by spring-projects.

the class JwtBearerTokenAuthenticationConverter method convert.

@Override
public AbstractAuthenticationToken convert(Jwt jwt) {
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt());
    Map<String, Object> attributes = jwt.getClaims();
    AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
    Collection<GrantedAuthority> authorities = token.getAuthorities();
    OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, authorities);
    return new BearerTokenAuthentication(principal, accessToken, authorities);
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2AuthenticatedPrincipal(org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal) DefaultOAuth2AuthenticatedPrincipal(org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DefaultOAuth2AuthenticatedPrincipal(org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal)

Aggregations

AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)37 GrantedAuthority (org.springframework.security.core.GrantedAuthority)19 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)17 Jwt (org.springframework.security.oauth2.jwt.Jwt)16 Test (org.junit.jupiter.api.Test)15 Authentication (org.springframework.security.core.Authentication)13 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)12 WebAuthenticationDetails (org.springframework.security.web.authentication.WebAuthenticationDetails)10 User (org.springframework.security.core.userdetails.User)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 SignedJWT (com.nimbusds.jwt.SignedJWT)3 ParseException (java.text.ParseException)3 ArrayList (java.util.ArrayList)3 RangerAuthenticationProvider (org.apache.ranger.security.handler.RangerAuthenticationProvider)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 Collection (java.util.Collection)2