Search in sources :

Example 11 with WebAuthenticationDetails

use of org.springframework.security.web.authentication.WebAuthenticationDetails in project Asqatasun by Asqatasun.

the class LoginController method doGuestAutoLogin.

private void doGuestAutoLogin(HttpServletRequest request, String guestUser) {
    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(guestUser, guestPassword);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication guest = authenticationManager.authenticate(token);
        Logger.getLogger(this.getClass()).debug("Logging in with [{}]" + guest.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(guest);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        Logger.getLogger(this.getClass()).debug("Failure in autoLogin", e);
    }
}
Also used : WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException)

Example 12 with WebAuthenticationDetails

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

the class AtlasKnoxSSOAuthenticationFilter method doFilter.

/*
     * doFilter of AtlasKnoxSSOAuthenticationFilter is the first in the filter list so in this it check for the request
     * if the request is from browser and sso is enabled then it process the request against knox sso
     * else if it's ssoenable and the request is with local login string then it show's the appropriate msg
     * else if ssoenable is false then it contiunes with further filters as it was before sso
     */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("X-Frame-Options", "DENY");
    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }
    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            //if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                //if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    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);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {
                // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SignedJWT(com.nimbusds.jwt.SignedJWT) 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) ParseException(java.text.ParseException)

Example 13 with WebAuthenticationDetails

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

the class WebAuthenticationDetailsMixinTests method webAuthenticationDetailsSerializeTest.

@Test
public void webAuthenticationDetailsSerializeTest() throws JsonProcessingException, JSONException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("/localhost");
    request.setSession(new MockHttpSession(null, "1"));
    WebAuthenticationDetails details = new WebAuthenticationDetails(request);
    String actualJson = mapper.writeValueAsString(details);
    JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) MockHttpSession(org.springframework.mock.web.MockHttpSession) Test(org.junit.Test)

Example 14 with WebAuthenticationDetails

use of org.springframework.security.web.authentication.WebAuthenticationDetails in project ORCID-Source by ORCID.

the class ShibbolethController method signinHandler.

@RequestMapping(value = { "/signin" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers, ModelAndView mav) {
    LOGGER.info("Headers for shibboleth sign in: {}", headers);
    checkEnabled();
    mav.setViewName("social_link_signin");
    String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
    mav.addObject("providerId", shibIdentityProvider);
    String displayName = institutionalSignInManager.retrieveDisplayName(headers);
    mav.addObject("accountId", displayName);
    RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
    if (remoteUser == null) {
        LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
        identityProviderManager.incrementFailedCount(shibIdentityProvider);
        mav.addObject("unsupportedInstitution", true);
        mav.addObject("institutionContactEmail", identityProviderManager.retrieveContactEmailByProviderid(shibIdentityProvider));
        return mav;
    }
    // Check if the Shibboleth user is already linked to an ORCID account.
    // If so sign them in automatically.
    UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
    if (userConnectionEntity != null) {
        LOGGER.info("Found existing user connection: {}", userConnectionEntity);
        HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
        if (!checkHeadersResult.isSuccess()) {
            mav.addObject("headerCheckFailed", true);
            return mav;
        }
        try {
            // Check if the user has been notified
            if (!UserConnectionStatus.NOTIFIED.equals(userConnectionEntity.getConnectionSatus())) {
                try {
                    institutionalSignInManager.sendNotification(userConnectionEntity.getOrcid(), shibIdentityProvider);
                    userConnectionEntity.setConnectionSatus(UserConnectionStatus.NOTIFIED);
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("Unable to send institutional sign in notification to user " + userConnectionEntity.getOrcid(), e);
                }
            }
            PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), remoteUser.getUserId());
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            userConnectionEntity.setLastLogin(new Date());
            userConnectionManager.update(userConnectionEntity);
        } catch (AuthenticationException e) {
            // this should never happen
            SecurityContextHolder.getContext().setAuthentication(null);
            LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
        }
        return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
    } else {
        // To avoid confusion, force the user to login to ORCID again
        mav.addObject("linkType", "shibboleth");
        mav.addObject("firstName", (headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER));
        mav.addObject("lastName", (headers.get(InstitutionalSignInManager.SN_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.SN_HEADER));
    }
    return mav;
}
Also used : HeaderCheckResult(org.orcid.pojo.HeaderCheckResult) RemoteUser(org.orcid.pojo.RemoteUser) AuthenticationException(org.springframework.security.core.AuthenticationException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) Date(java.util.Date) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 15 with WebAuthenticationDetails

use of org.springframework.security.web.authentication.WebAuthenticationDetails in project ORCID-Source by ORCID.

the class SocialController method signinHandler.

@RequestMapping(value = { "/access" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response) {
    SocialType connectionType = socialContext.isSignedIn(request, response);
    if (connectionType != null) {
        Map<String, String> userMap = retrieveUserDetails(connectionType);
        String providerId = connectionType.value();
        String userId = socialContext.getUserId();
        UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
        if (userConnectionEntity != null) {
            if (userConnectionEntity.isLinked()) {
                UserconnectionPK pk = new UserconnectionPK(userId, providerId, userMap.get("providerUserId"));
                userConnectionManager.updateLoginInformation(pk);
                String aCredentials = new StringBuffer(providerId).append(":").append(userMap.get("providerUserId")).toString();
                PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), aCredentials);
                token.setDetails(new WebAuthenticationDetails(request));
                Authentication authentication = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
            } else {
                ModelAndView mav = new ModelAndView();
                mav.setViewName("social_link_signin");
                mav.addObject("providerId", providerId);
                mav.addObject("accountId", getAccountIdForDisplay(userMap));
                mav.addObject("linkType", "social");
                mav.addObject("emailId", (userMap.get("email") == null) ? "" : userMap.get("email"));
                mav.addObject("firstName", (userMap.get("firstName") == null) ? "" : userMap.get("firstName"));
                mav.addObject("lastName", (userMap.get("lastName") == null) ? "" : userMap.get("lastName"));
                return mav;
            }
        } else {
            throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
        }
    } else {
        throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) SocialType(org.orcid.frontend.spring.web.social.config.SocialType) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) UserconnectionPK(org.orcid.persistence.jpa.entities.UserconnectionPK) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WebAuthenticationDetails (org.springframework.security.web.authentication.WebAuthenticationDetails)18 Authentication (org.springframework.security.core.Authentication)11 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 Date (java.util.Date)3 Test (org.junit.Test)3 EventBuilder (org.opennms.netmgt.model.events.EventBuilder)3 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)3 AuthenticationException (org.springframework.security.core.AuthenticationException)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 UserconnectionEntity (org.orcid.persistence.jpa.entities.UserconnectionEntity)2 MockHttpSession (org.springframework.mock.web.MockHttpSession)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 AuthenticationFailureBadCredentialsEvent (org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent)2 GrantedAuthority (org.springframework.security.core.GrantedAuthority)2 User (org.springframework.security.core.userdetails.User)2 UserDetails (org.springframework.security.core.userdetails.UserDetails)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2