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;
}
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;
}
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);
}
}
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\"}"));
}
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);
}
}
Aggregations