Search in sources :

Example 96 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project molgenis by molgenis.

the class TwoFactorAuthenticationController method validate.

@PostMapping(TWO_FACTOR_VALIDATION_URI)
public String validate(Model model, @RequestParam String verificationCode) {
    String redirectUri = "redirect:/";
    try {
        TwoFactorAuthenticationToken authToken = new TwoFactorAuthenticationToken(verificationCode, null);
        Authentication authentication = authenticationProvider.authenticate(authToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (AuthenticationException err) {
        model.addAttribute(MolgenisLoginController.ERROR_MESSAGE_ATTRIBUTE, determineErrorMessage(err));
        redirectUri = VIEW_2FA_CONFIGURED_MODAL;
    }
    return redirectUri;
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) TwoFactorAuthenticationToken(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationToken) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 97 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project testcases by coheigea.

the class SpringSecurityUTValidator method validate.

public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }
    // Validate the UsernameToken
    UsernameToken usernameToken = credential.getUsernametoken();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }
    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - digest passwords are not accepted");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (usernameToken.getPassword() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - no password was provided");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    // Validate it via Spring Security
    // Set a Subject up
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(usernameToken.getName(), usernameToken.getPassword());
    Subject subject = new Subject();
    subject.getPrincipals().add(authToken);
    Set<Authentication> authentications = subject.getPrincipals(Authentication.class);
    Authentication authenticated = null;
    try {
        authenticated = authenticationManager.authenticate(authentications.iterator().next());
    } catch (AuthenticationException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (!authenticated.isAuthenticated()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    for (GrantedAuthority authz : authenticated.getAuthorities()) {
        System.out.println("Granted: " + authz.getAuthority());
    }
    // Authorize request
    if (accessDecisionManager != null && !requiredRoles.isEmpty()) {
        List<ConfigAttribute> attributes = SecurityConfig.createList(requiredRoles.toArray(new String[requiredRoles.size()]));
        for (ConfigAttribute attr : attributes) {
            System.out.println("Attr: " + attr.getAttribute());
        }
        accessDecisionManager.decide(authenticated, this, attributes);
    }
    credential.setSubject(subject);
    return credential;
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Subject(javax.security.auth.Subject)

Example 98 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project jhipster-registry by jhipster.

the class UserJWTController method authorize.

@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException ae) {
        log.trace("Authentication exception trace: {}", ae);
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) PostMapping(org.springframework.web.bind.annotation.PostMapping) Timed(com.codahale.metrics.annotation.Timed)

Example 99 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project jhipster-registry by jhipster.

the class UserJWTControllerTest method authorizeTest.

@Test
public void authorizeTest() throws Exception {
    // Normal authentication
    LoginVM vm = new LoginVM();
    vm.setUsername("admin");
    vm.setPassword("admin");
    vm.setRememberMe(true);
    Mockito.doReturn("fakeToken").when(tokenProvider).createToken(Mockito.any(Authentication.class), Mockito.anyBoolean());
    mock.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL).content(new ObjectMapper().writeValueAsString(vm))).andExpect(content().string("{\"id_token\":\"fakeToken\"}")).andExpect(status().isOk());
    // Authentication exception throws
    Mockito.doThrow(new AuthenticationException(null) {
    }).when(tokenProvider).createToken(Mockito.any(Authentication.class), Mockito.anyBoolean());
    MvcResult res = mock.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL).content("{\"username\":\"fakeUsername\",\"password\":\"fakePassword\",\"rememberMe\":false}")).andExpect(status().isUnauthorized()).andReturn();
    assertTrue(res.getResponse().getContentAsString().startsWith("{\"AuthenticationException\""));
    // Bad credentials
    vm.setUsername("badcred");
    vm.setPassword("badcred");
    Mockito.doThrow(new BadCredentialsException("Bad credentials")).when(authenticationManager).authenticate(new UsernamePasswordAuthenticationToken(vm.getUsername(), vm.getPassword()));
    mock.perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL).content(new ObjectMapper().writeValueAsString(vm))).andExpect(status().isUnauthorized()).andExpect(content().string("{\"AuthenticationException\":\"Bad credentials\"}"));
}
Also used : LoginVM(io.github.jhipster.registry.web.rest.vm.LoginVM) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) MvcResult(org.springframework.test.web.servlet.MvcResult) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 100 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project syncope by apache.

the class JWTAuthenticationFilter method doFilterInternal.

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws ServletException, IOException {
    String auth = request.getHeader(HttpHeaders.AUTHORIZATION);
    String[] parts = auth == null ? null : auth.split(" ");
    if (parts == null || parts.length != 2 || !"Bearer".equals(parts[0])) {
        chain.doFilter(request, response);
        return;
    }
    String stringToken = parts[1];
    LOG.debug("JWT received: {}", stringToken);
    try {
        credentialChecker.checkIsDefaultJWSKeyInUse();
        JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(stringToken);
        JWTSSOProvider jwtSSOProvider = dataAccessor.getJWTSSOProvider(consumer.getJwtClaims().getIssuer());
        if (!consumer.verifySignatureWith(jwtSSOProvider)) {
            throw new BadCredentialsException("Invalid signature found in JWT");
        }
        Authentication authentication = authenticationManager.authenticate(new JWTAuthentication(consumer.getJwtClaims(), authenticationDetailsSource.buildDetails(request)));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    } catch (JwsException e) {
        SecurityContextHolder.clearContext();
        this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("Invalid JWT: " + stringToken, e));
    } catch (AuthenticationException e) {
        SecurityContextHolder.clearContext();
        this.authenticationEntryPoint.commence(request, response, e);
    }
}
Also used : JwsException(org.apache.cxf.rs.security.jose.jws.JwsException) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)156 Authentication (org.springframework.security.core.Authentication)78 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)25 Test (org.junit.Test)24 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)15 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 Map (java.util.Map)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6 InternalAuthenticationServiceException (org.springframework.security.authentication.InternalAuthenticationServiceException)6