Spring Boot: How to tell client that account password has expired? - spring-boot

I have a simple login form and a login() method in a controller :
#PostMapping("/login")
public ResponseEntity<UserVO> login(#RequestBody UserVO userVO) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
userVO.getUsername(),
userVO.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication( authentication );
// ...
return ResponseEntity.ok( loggedInUser );
}
I have a users table with columns :
`username`
`password`
`password_expiration`
`account_expiration`
`account_locked`
`account_disabled`
When I set the value of column password_expiration to expire a user's password, Spring Boot's authenticationManager.authenticate() method throws an AccountExpiredException exception at next login attempt :
package org.springframework.security.authentication;
public class AccountExpiredException extends AccountStatusException {
public AccountExpiredException(String msg) {
super(msg);
}
public AccountExpiredException(String msg, Throwable t) {
super(msg, t);
}
}
and JSON response is :
{
"timestamp":"2018-07-26T22:53:05.392+0000",
"status":401,
"error":"Unauthorized",
"message":"Unauthorized",
"path":"/login"
}
I get the same JSON response (401 error code) whenever the password is wrong or one of the methods of UserVO (which in turn implements UserDetails) return false :
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
So far so good.
When the user logs in and his/her password is expired I want to redirect the UI to a mandatory password change page. But how ? I always get the same JSON respons.
1) Since the JSON output that is returned is always a HTTP 401 error, how can I get a more fine grained response ? (How to tell client code that the password has expired?)
2) Is it generally considered good or bad practice to inform the user that his/her account is locked / expired / disabled ? (good user experience vs giving away info about account state to hackers)

Maybe not the best solution, but I solved it by setting the "message" field :
#Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
#Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
String message = "Unauthorized";
if ( authException instanceof BadCredentialsException )
message = AUTH_CREDENTIALS_BAD;
else if ( authException instanceof CredentialsExpiredException )
message = AUTH_CREDENTIALS_EXPIRED;
else if ( authException instanceof LockedException )
message = AUTH_ACCOUNT_LOCKED;
else if ( authException instanceof DisabledException )
message = AUTH_ACCOUNT_DISABLED;
else if ( authException instanceof AccountExpiredException )
message = AUTH_ACCOUNT_EXPIRED;
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, message );
}
}
Now I get this as response :
{
"timestamp":"2018-07-27T12:54:53.097+0000",
"status":401,
"error":"Unauthorized",
"message":"credentials_expired",
"path":"/login"
}

Related

Spring-security - invalid login always return 403 instead of appropriate errors

I am trying to input some more "accurate" error handling for invalid logins.
The three main objectives: invalid password, account disabled, invalid email.
The current calling hierarchy is the following:
Attempted login requests
#Override // THIS OVERRIDES THE DEFAULT SPRING SECURITY IMPLEMENTATION
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String email = request.getParameter("email");
String password = request.getParameter("password");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(email, password);
return authManager.authenticate(authToken);
}
This calls another override method where I tried to insert error handling because it has access to the userRepo and object. The issue here is if the AccountLockedException or fails on email finding or password verification, it will always reutrn a 403 and no indication of the thrown exception.
#SneakyThrows
#Override // THIS OVERWRITES THE DEFAULT SPRING SECURITY ONE
public UserDetails loadUserByUsername(String email){
User user = findUserByEmail(email);
if ( user != null){
if (user.isEnabled()){
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
user.getRoles().forEach(role -> { authorities.add(new SimpleGrantedAuthority(role.getName()));});
sucessfulLogin(user);
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities);
}
else { throw new AccountLockedException("Account disabled"); }
}
}
However, what I have found this previous method on throwing will call this additional override method (in the same class as the attempted authentication)
#Override // DO SOMETHING WITH THIS TO PREVENT BRUTE FORCE ATTACKS WITH LIMITED NUMBER OF ATTEMPTS IN A TIME-FRAME
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
System.out.println("aaa");
super.unsuccessfulAuthentication(request, response, failed);
}
Though, at this point it will display the following:
this option gets shown when the password is incorrect.
this option gets shown when the account is disabeld.
this option gets shown when the email is incorrect.
My question is. Firstly how do I appropriately distinguish between these errors and secondly send appropriate http responses based on these errors?
if (failed != null) {
if (failed.getMessage() == "AccountLockedException") {
response.setStatus(403);
} // if account is disabled
else if (failed.getMessage() == "EntityNotFoundException") {
response.setStatus(400);
} // if email incorrect
else if (failed.getMessage() == "Bad credentials") {
response.setStatus(400);
} // if password incorrect
else {
System.out.println("some kind of other authentication error");
response.setStatus(418); // some random error incase this ever happens
}

How to pass/inject a session-specific info to the below level?

I have a rest controller and I want to give means to access to a "Session" bean that I create by extracting the infos from the http header.
For this reason I created an HttpInterceptor that pre-handles the request by extracting the headers:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String remoteUser = request.getHeader("x-remote-user");
log.info("Helo {}", remoteUser);
MySession session = new MySession();
session.setUser(remoteUser);
//what now?
return true;
}
But, how can I do something like this:
public MyController {
public ResponseEntitity<String> action(Request a){
MySession user = getUserSession(); //here I should be able to retrieve the session for that specific user
}
}

authenticated and anonymous for the same endpoind (spring security)

What i want is, for
localhost:8080/home -> should be open to only authenticated - home page after login
localhost:8080/home?msg=asdsada -> should be open to anonymous - for login errors like wrong password
This is endpoind:
#GetMapping(value = { "/home"})
public ModelAndView getLoginPage(
#RequestParam(value = "msg", required = false) String message) throws IOException
I tried to add this to security config of spring
.regexMatchers("/home").authenticated()
.regexMatchers("/home?msg=.*").permitAll()
So config became like this:
http
.authorizeRequests().antMatchers(anonymousEndpoints).anonymous()
.antMatchers(permittedEndpoints).permitAll()
.regexMatchers("/home").authenticated()
.regexMatchers("/home?msg=.*").anonymous()
.and()
.authorizeRequests().anyRequest().fullyAuthenticated()
But for wrong password, it does not go to endpoind
localhost:8080/home?msg=asdsada
For logged user, it can go to
localhost:8080/home
also it can go to
localhost:8080/home?msg=asdsada
What am I doing wrong? I can also use endpoind to check if logged in or not. Like:
But i want spring scurity to do this. Give 403 forbidden for example.
#GetMapping(value = { "/home"})
public ModelAndView getLoginPage(
#RequestParam(value = "msg", required = false) String message) throws IOException{
Authentication authentication = SecurityUtil.getAuthentication(false);
if (authentication != null) {
logger.info("User: {} already logged in, redirecting to dashboard", authentication.getName());
web.response.sendRedirect("/dashboard");
return null;
}
else{//not logged in
if (msg != null)//and msg is not null so like wrong password
//do smth
}
return null;
}
Don't configure the specific path in Spring Security Config, just analyze it in the controller method. In config set permitAll for this path, but add an authentication or principal parameter in the method signature:
#GetMapping(value = { "/home"})
public ModelAndView getLoginPage(#RequestParam(value = "msg", required = false) String message, Authentication authentication) throws IOException {
if (msg != null) {
...
} else if (!authentication.isAuthenticated()) {
...
}
...
}
P.S. Method arguments: https://docs.spring.io/spring/docs/5.2.x/spring-framework-reference/web.html#mvc-ann-arguments

Webflux JWT Authorization not working fine

I am following a tutorial about JWT in a spring reactive context (webflux).
The token generation is working fine, however the authorization is not working when I use the Authorization with bearer
Here is what I have done:
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class WebSecurityConfig{
#Autowired private JWTReactiveAuthenticationManager authenticationManager;
#Autowired private SecurityContextRepository securityContext;
#Bean public SecurityWebFilterChain configure(ServerHttpSecurity http){
return http.exceptionHandling()
.authenticationEntryPoint((swe , e) -> {
return Mono.fromRunnable(()->{
System.out.println( "authenticationEntryPoint user trying to access unauthorized api end points : "+
swe.getRequest().getRemoteAddress()+
" in "+swe.getRequest().getPath());
swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
});
}).accessDeniedHandler((swe, e) -> {
return Mono.fromRunnable(()->{
System.out.println( "accessDeniedHandler user trying to access unauthorized api end points : "+
swe.getPrincipal().block().getName()+
" in "+swe.getRequest().getPath());
swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
});
})
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authenticationManager)
.securityContextRepository(securityContext)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/auth/login").permitAll()
.anyExchange().authenticated()
.and()
.build();
}
As you can see, I want to simply deny all not authorized requests other than login or options based ones.
The login is working fine and I'm getting a token.
But trying to logout (a tweak that I implemented my self to make it state-full since I m only learning) is not working.
Here is my logout controller:
#RestController
#RequestMapping(AuthController.AUTH)
public class AuthController {
static final String AUTH = "/auth";
#Autowired
private AuthenticationService authService;
#PostMapping("/login")
public Mono<ResponseEntity<?>> login(#RequestBody AuthRequestParam arp) {
String username = arp.getUsername();
String password = arp.getPassword();
return authService.authenticate(username, password);
}
#PostMapping("/logout")
public Mono<ResponseEntity<?>> logout(#RequestBody LogoutRequestParam lrp) {
String token = lrp.getToken();
return authService.logout(token);
}
}
The logout request is as below:
As stated in images above, I believe that I m doing fine, however I m getting the error log message:
authenticationEntryPoint user trying to access unauthorized api end points : /127.0.0.1:45776 in /auth/logout
Here is my security context content:
/**
* we use this class to handle the bearer token extraction
* and pass it to the JWTReactiveAuthentication manager so in the end
* we produce
*
* simply said we extract the authorization we authenticate and
* depending on our implementation we produce a security context
*/
#Component
public class SecurityContextRepository implements ServerSecurityContextRepository {
#Autowired
private JWTReactiveAuthenticationManager authenticationManager;
#Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
ServerHttpRequest request = swe.getRequest();
String authorizationHeaderContent = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if( authorizationHeaderContent !=null && !authorizationHeaderContent.isEmpty() && authorizationHeaderContent.startsWith("Bearer ")){
String token = authorizationHeaderContent.substring(7);
Authentication authentication = new UsernamePasswordAuthenticationToken(token, token);
return this.authenticationManager.authenticate(authentication).map((auth) -> {
return new SecurityContextImpl(auth);
});
}
return Mono.empty();
}
#Override
public Mono<Void> save(ServerWebExchange arg0, SecurityContext arg1) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
I'm unable to see or find any issue or error that I have made. Where is the mistake?
There's a difference in writing
//Wrong
Jwts.builder()
.setSubject(username)
.setClaims(claims)
and
//Correct
Jwts.builder()
.setClaims(claims)
.setSubject(username)
Indeed, look at setSubject method in the DefaultJwtBuilder class :
#Override
public JwtBuilder setSubject(String sub) {
if (Strings.hasText(sub)) {
ensureClaims().setSubject(sub);
} else {
if (this.claims != null) {
claims.setSubject(sub);
}
}
return this;
}
When setSubject(username) is called first, ensureClaims() creates a DefaultClaims without yours and if you call setClaims(claims) the precedent subject is lost ! This JWT builder is bogus.
Otherwise, you're importing the wrong Role class in JWTReactiveAuthenticationManager, you have to replace :
import org.springframework.context.support.BeanDefinitionDsl.Role;
by
import com.bridjitlearning.www.jwt.tutorial.domain.Role;
Last and not least, validateToken() will return always false because of the check(token). put call is coming too late, you have to be aware of that. Either you remove this check or you move the put execution before calling the check method.
I'am not sure about what you want to do with resignTokenMemory, so i'll let you fix it by your own:
public Boolean validateToken(String token) {
return !isTokenExpired(token) && resignTokenMemory.check(token);
}
Another thing, your token is valid only 28,8 second, for testing raison i recommend you to expiraiton * 1000.

Spring security perform validations for custom login form

I need to do some validations on the login form before calling the authenticationManager for authentication. Have been able to achieve it with help from one existing post - How to make extra validation in Spring Security login form?
Could someone please suggest me whether I am following the correct approach or missing out something? Particularly, I was not very clear as to how to show the error messages.
In the filter I use validator to perform validations on the login field and in case there are errors, I throw an Exception (which extends AuthenticationException) and encapsulate the Errors object. A getErrors() method is provided to the exception class to retrieve the errors.
Since in case of any authentication exception, the failure handler stores the exception in the session, so in my controller, I check for the exception stored in the session and if the exception is there, fill the binding result with the errors object retrieved from the my custom exception (after checking runtime instance of AuthenticationException)
The following are my code snaps -
LoginFilter class
public class UsernamePasswordLoginAuthenticationFilter extends
UsernamePasswordAuthenticationFilter {
#Autowired
private Validator loginValidator;
/* (non-Javadoc)
* #see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
Login login = new Login();
login.setUserId(request.getParameter("userId"));
login.setPassword(request.getParameter("password"));
Errors errors = new BeanPropertyBindingResult(login, "login");
loginValidator.validate(login, errors);
if(errors.hasErrors()) {
throw new LoginAuthenticationValidationException("Authentication Validation Failure", errors);
}
return super.attemptAuthentication(request, response);
}
}
Controller
#Controller
public class LoginController {
#RequestMapping(value="/login", method = RequestMethod.GET)
public String loginPage(#ModelAttribute("login") Login login, BindingResult result, HttpServletRequest request) {
AuthenticationException excp = (AuthenticationException)
request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if(excp != null) {
if (excp instanceof LoginAuthenticationValidationException) {
LoginAuthenticationValidationException loginExcp = (LoginAuthenticationValidationException) excp;
result.addAllErrors(loginExcp.getErrors());
}
}
return "login";
}
#ModelAttribute
public void initializeForm(ModelMap map) {
map.put("login", new Login());
}
This part in the controller to check for the instance of the Exception and then taking out the Errors object, does not look a clean approach. I am not sure whether this is the only way to handle it or someone has approached it in any other way? Please provide your suggestions.
Thanks!
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView signInPage(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView mav = new ModelAndView();
//Initially when you hit on login url then error and logout both null
if (error != null) {
mav.addObject("error", "Invalid username and password!");
}
if (logout != null) {
mav.addObject("msg", "You've been logged out successfully.");
}
mav.setViewName("login/login.jsp");
}
Now if in case login become unsuccessfull then it will again hit this url with error append in its url as in spring security file you set the failure url.
Spring security file: -authentication-failure-url="/login?error=1"
Then your URl become url/login?error=1
Then automatically signInPage method will call and with some error value.Now error is not null and you can set any string corresponding to url and we can show on jsp using these following tags:-
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>

Resources