Search in sources :

Example 51 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project molgenis by molgenis.

the class AuthenticationAuthoritiesUpdaterImplTest method testUpdateAuthenticationAnonymousAuthenticationToken.

@Test
public void testUpdateAuthenticationAnonymousAuthenticationToken() {
    String key = "key";
    Object principal = mock(Object.class);
    AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken(key, principal, singletonList(mock(GrantedAuthority.class)));
    Authentication updatedAuthentication = authenticationAuthoritiesUpdaterImpl.updateAuthentication(anonymousAuthenticationToken, updatedAuthorities);
    assertEquals(updatedAuthentication, new AnonymousAuthenticationToken(key, principal, updatedAuthorities));
}
Also used : Authentication(org.springframework.security.core.Authentication) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Test(org.testng.annotations.Test)

Example 52 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project molgenis by molgenis.

the class AuthenticationAuthoritiesUpdaterImpl method updateAuthentication.

@Override
public Authentication updateAuthentication(Authentication authentication, List<GrantedAuthority> updatedAuthorities) {
    Authentication newAuthentication;
    if (authentication instanceof TwoFactorAuthenticationToken) {
        TwoFactorAuthenticationToken twoFactorAuthenticationToken = (TwoFactorAuthenticationToken) authentication;
        newAuthentication = new TwoFactorAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, twoFactorAuthenticationToken.getVerificationCode(), twoFactorAuthenticationToken.getSecretKey());
    } else if (authentication instanceof SystemSecurityToken) {
        newAuthentication = authentication;
    } else if (authentication instanceof RestAuthenticationToken) {
        RestAuthenticationToken restAuthenticationToken = (RestAuthenticationToken) authentication;
        newAuthentication = new RestAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, restAuthenticationToken.getToken());
    } else if (authentication instanceof RecoveryAuthenticationToken) {
        RecoveryAuthenticationToken recoveryAuthenticationToken = (RecoveryAuthenticationToken) authentication;
        newAuthentication = new RecoveryAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities, recoveryAuthenticationToken.getRecoveryCode());
    } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
        newAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), updatedAuthorities);
    } else if (authentication instanceof RunAsUserToken) {
        RunAsUserToken runAsUserToken = (RunAsUserToken) authentication;
        newAuthentication = new RunAsUserTokenDecorator(runAsUserToken, updatedAuthorities);
    } else if (authentication instanceof AnonymousAuthenticationToken) {
        AnonymousAuthenticationToken anonymousAuthenticationToken = (AnonymousAuthenticationToken) authentication;
        newAuthentication = new AnonymousAuthenticationTokenDecorator(anonymousAuthenticationToken, updatedAuthorities);
    } else {
        throw new SessionAuthenticationException(format("Unknown authentication type '%s'", authentication.getClass().getSimpleName()));
    }
    return newAuthentication;
}
Also used : RecoveryAuthenticationToken(org.molgenis.security.twofactor.auth.RecoveryAuthenticationToken) SessionAuthenticationException(org.springframework.security.web.authentication.session.SessionAuthenticationException) RunAsUserToken(org.springframework.security.access.intercept.RunAsUserToken) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SystemSecurityToken(org.molgenis.security.core.runas.SystemSecurityToken) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) RestAuthenticationToken(org.molgenis.security.token.RestAuthenticationToken) TwoFactorAuthenticationToken(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationToken)

Example 53 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project alien4cloud by alien4cloud.

the class AuthController method getLoginStatus.

/**
 * Get the current user's status (login, roles etc.).
 *
 * @return The current user's status wrapped in a {@link RestResponse} object.
 */
@ApiOperation(value = "Get the current authentication status and user's roles.", notes = "Return the current user's status and it's roles.")
@RequestMapping(value = "/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RestResponse<UserStatus> getLoginStatus() {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final UserStatus userStatus = new UserStatus();
    if (auth == null) {
        userStatus.setIsLogged(false);
    } else {
        userStatus.setIsLogged(auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken));
        userStatus.setUsername(auth.getName());
        if (auth.getPrincipal() instanceof User) {
            userStatus.setGithubUsername(((User) auth.getPrincipal()).getFirstName());
            userStatus.setGroups(((User) auth.getPrincipal()).getGroups());
        }
        for (GrantedAuthority role : auth.getAuthorities()) {
            userStatus.getRoles().add(role.getAuthority());
        }
    }
    if (env.acceptsProfiles("github-auth")) {
        userStatus.setAuthSystem("github");
    } else if (samlEnabled) {
        userStatus.setAuthSystem("saml");
    } else {
        userStatus.setAuthSystem("alien");
    }
    return RestResponseBuilder.<UserStatus>builder().data(userStatus).build();
}
Also used : User(alien4cloud.security.model.User) Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) UserStatus(alien4cloud.rest.model.UserStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 54 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project rap by entirej.

the class EJSpnegoAuthenticationProcessingFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (skipIfAlreadyAuthenticated) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated() && (existingAuth instanceof AnonymousAuthenticationToken) == false) {
            chain.doFilter(request, response);
            return;
        }
    }
    String header = request.getHeader("Authorization");
    if (header != null && (header.startsWith("Negotiate ") || header.startsWith("Kerberos "))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(header.indexOf(" ") + 1).getBytes("UTF-8");
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationRequest);
        } catch (AuthenticationException e) {
            // That shouldn't happen, as it is most likely a wrong
            // configuration on the server side
            logger.warn("Negotiate Header was invalid: " + header, e);
            SecurityContextHolder.clearContext();
            // if (failureHandler != null)
            // {
            // failureHandler.onAuthenticationFailure(request, response, e);
            // }
            // else
            // {
            // response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            // response.flushBuffer();
            // }
            String url = getCustomRedirectUrl(request);
            if (url == null) {
                url = request.getContextPath() + "/login.html";
            }
            ((HttpServletResponse) response).sendRedirect(url);
            return;
        }
        sessionStrategy.onAuthentication(authentication, request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (successHandler != null) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) KerberosServiceRequestToken(org.springframework.security.kerberos.authentication.KerberosServiceRequestToken)

Example 55 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project midpoint by Evolveum.

the class MidpointSaml2LogoutRequestResolver method resolve.

@Override
public Saml2LogoutRequest resolve(HttpServletRequest httpServletRequest, Authentication authentication) {
    Saml2AuthenticationToken token = null;
    if (authentication instanceof MidpointAuthentication) {
        ModuleAuthentication authModule = ((MidpointAuthentication) authentication).getProcessingModuleAuthentication();
        if (authModule instanceof Saml2ModuleAuthenticationImpl) {
            if (authModule.getAuthentication() instanceof Saml2AuthenticationToken) {
                token = (Saml2AuthenticationToken) authModule.getAuthentication();
            } else if ((authModule.getAuthentication() instanceof PreAuthenticatedAuthenticationToken || authModule.getAuthentication() instanceof AnonymousAuthenticationToken) && authModule.getAuthentication().getDetails() instanceof Saml2AuthenticationToken) {
                token = (Saml2AuthenticationToken) authModule.getAuthentication().getDetails();
            }
        }
    } else if (authentication instanceof AnonymousAuthenticationToken && authentication.getDetails() instanceof Saml2AuthenticationToken) {
        token = (Saml2AuthenticationToken) authentication.getDetails();
    }
    if (token != null) {
        AuthenticatedPrincipal principal = token.getDetails() instanceof AuthenticatedPrincipal ? (AuthenticatedPrincipal) token.getDetails() : null;
        if (!(principal instanceof Saml2AuthenticatedPrincipal)) {
            String name = token.getRelyingPartyRegistration().getEntityId();
            String relyingPartyRegistrationId = token.getRelyingPartyRegistration().getRegistrationId();
            principal = new Saml2AuthenticatedPrincipal() {

                @Override
                public String getName() {
                    return name;
                }

                @Override
                public String getRelyingPartyRegistrationId() {
                    return relyingPartyRegistrationId;
                }
            };
        }
        return resolver.resolve(httpServletRequest, new Saml2Authentication(principal, token.getSaml2Response(), null));
    }
    return resolver.resolve(httpServletRequest, authentication);
}
Also used : ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) Saml2Authentication(org.springframework.security.saml2.provider.service.authentication.Saml2Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Saml2ModuleAuthenticationImpl(com.evolveum.midpoint.authentication.impl.module.authentication.Saml2ModuleAuthenticationImpl) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Saml2AuthenticationToken(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken) Saml2AuthenticatedPrincipal(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal) Saml2AuthenticatedPrincipal(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal) AuthenticatedPrincipal(org.springframework.security.core.AuthenticatedPrincipal)

Aggregations

AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)87 Authentication (org.springframework.security.core.Authentication)37 Test (org.junit.jupiter.api.Test)22 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)17 ArrayList (java.util.ArrayList)14 GrantedAuthority (org.springframework.security.core.GrantedAuthority)13 SecurityContext (org.springframework.security.core.context.SecurityContext)10 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)8 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)7 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)7 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)6 Before (org.junit.Before)5 Test (org.junit.Test)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 FilterChain (jakarta.servlet.FilterChain)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3