Search in sources :

Example 6 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project motech by motech.

the class UserContextServiceImpl method refreshAllUsersContextIfActive.

@Override
@Transactional
public void refreshAllUsersContextIfActive() {
    Collection<HttpSession> sessions = sessionHandler.getAllSessions();
    MotechUser user;
    LOGGER.info("Refreshing context for all active users, number of sessions: {}", sessions.size());
    for (HttpSession session : sessions) {
        SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (context != null) {
            Authentication authentication = context.getAuthentication();
            AbstractAuthenticationToken token;
            User userInSession = (User) authentication.getPrincipal();
            user = motechUsersDao.findByUserName(userInSession.getUsername());
            if (user == null) {
                LOGGER.warn("User {} has a session, but does not exist", userInSession.getUsername());
            } else {
                LOGGER.debug("Refreshing context for user {}", user.getUserName());
                token = getToken(authentication, user);
                context.setAuthentication(token);
            }
        }
    }
    LOGGER.info("Refreshed context for all active users");
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) User(org.springframework.security.core.userdetails.User) MotechUser(org.motechproject.security.domain.MotechUser) HttpSession(javax.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project motech by motech.

the class UserContextServiceImpl method refreshUserContextIfActive.

@Override
@Transactional
public void refreshUserContextIfActive(String userName) {
    LOGGER.info("Refreshing context for user: {}", userName);
    MotechUser user = motechUsersDao.findByUserName(userName);
    Collection<HttpSession> sessions = sessionHandler.getAllSessions();
    for (HttpSession session : sessions) {
        SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (context != null) {
            Authentication authentication = context.getAuthentication();
            AbstractAuthenticationToken token;
            User userInSession = (User) authentication.getPrincipal();
            if (userInSession.getUsername().equals(userName)) {
                token = getToken(authentication, user);
                context.setAuthentication(token);
            }
        }
    }
    LOGGER.info("Refreshed context for user: {}", userName);
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) User(org.springframework.security.core.userdetails.User) MotechUser(org.motechproject.security.domain.MotechUser) HttpSession(javax.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Transactional(org.springframework.transaction.annotation.Transactional)

Example 8 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project ArTEMiS by ls1intum.

the class LtiAuthenticationSuccessListener method onApplicationEvent.

@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
    // Not fired on programmatic logins!
    if (event instanceof InteractiveAuthenticationSuccessEvent) {
        AbstractAuthenticationToken token = (AbstractAuthenticationToken) event.getSource();
        WebAuthenticationDetails authDetails = (WebAuthenticationDetails) token.getDetails();
        String sessionId = authDetails.getSessionId();
        ltiService.handleLaunchRequestForSession(sessionId);
    }
}
Also used : InteractiveAuthenticationSuccessEvent(org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails)

Example 9 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project 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());
                    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");
        responseWrapper.setHeader("X-Content-Type-Options", "nosniff");
        responseWrapper.setHeader("X-XSS-Protection", "1; mode=block");
        responseWrapper.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
        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) 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)

Example 10 with AbstractAuthenticationToken

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

the class JwtBearerTokenAuthenticationConverterTests method convertWhenJwtWithScopeAttributeThenBearerTokenAuthentication.

@Test
public void convertWhenJwtWithScopeAttributeThenBearerTokenAuthentication() {
    // @formatter:off
    Jwt jwt = Jwt.withTokenValue("token-value").claim("scope", "message:read message:write").header("header", "value").build();
    // @formatter:on
    AbstractAuthenticationToken token = this.converter.convert(jwt);
    assertThat(token).isInstanceOf(BearerTokenAuthentication.class);
    BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token;
    assertThat(bearerToken.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write"));
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

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