1

I am passing username and password from client application through json object and i am using UsernamePasswordAuthenticationFilter for authenticating user as suggested in answer https://stackoverflow.com/a/19572145/4070142 of question Spring Security and JSON Authentication.

My question is that where do i put check for authentication? I mean where do i put if(username.equals("user123")&&password.equals("password123")) {return true;}

For code please refer answer https://stackoverflow.com/a/19572145/4070142 of above linked question.

Community
  • 1
  • 1
doga
  • 471
  • 2
  • 9
  • 20
  • You don't. That is what spring security is doing for you, – M. Deinum Jun 09 '15 at 14:12
  • Yeah, Thats true, But somewhere we need to configure like in tag in configuration file. So if i put manually valid user credentials in tag then how do i link it with my custom filter tags? – doga Jun 09 '15 at 14:21
  • You give it an alias, and inject it into your filter. Although I wouldn't go for the solution you have in the other thread. Nor would I link to that thread but provide all the information here, it isn't really nice to have the people who want to help you click around to get all the information. – M. Deinum Jun 09 '15 at 14:31

1 Answers1

0

Actual username and password comparisons happen at authentication provider. UsernamePasswordAuthenticationFilter obtains username/pwd and passes on to authenticationManager, which inturn delegates it to authenticationProvider. In your case, you need to add a custom authentication provider as follows:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();
    if(username.equals("user123") && password.equals("password123")) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); //assign some role
        Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
        return auth; //return Authentication object, not true
    } else {
        return null;
    }
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

}

declare the new authentication provider in our configuration:

<authentication-manager>
    <authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

Reference:
https://danielkaes.wordpress.com/2013/02/20/custom-authentication-provider-in-spring/

charybr
  • 1,888
  • 24
  • 29