Reputation:
I know this has been answered so many times, but I am confused. I already have an Authentication mechanism in my application and I just want to use the authorization part of Spring MVC. I'm using Spring MVC 3 and Spring Security 3.
When I search on internet I found two solutions, the first one is to just implement AuthenticationProvider interface. Example1. The second one is to implement UserDetails and UserDetailsService, Example2 so I'm lost here.
----Update----
The second part of the Question is here. And the solution to the workaround.
Upvotes: 16
Views: 30927
Reputation: 1750
In most cases when only using usernames and passwords for authentications and roles for authorisation, implementing your own UserDetailsService is enough.
The flow of the username password authentication is then generally as follows:
So if the verification in the DaoAuthenticationProvider suits your needs. Then you'll only have to implement your own UserDetailsService and tweak the verification of the DaoAuthenticationProvider.
An example for the UserDetailsService using spring 3.1 is as follows:
Spring XML:
<security:authentication-manager>
<security:authentication-provider user-service-ref="myUserDetailsService" />
</security:authentication-manager>
<bean name="myUserDetailsService" class="x.y.MyUserDetailsService" />
UserDetailsService Implementation:
public MyUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Retrieve the user from wherever you store it, e.g. a database
MyUserClass user = ...;
if (user == null) {
throw new UsernameNotFoundException("Invalid username/password.");
}
Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("Role1","role2","role3");
return new User(user.getUsername(), user.getPassword(), authorities);
}
}
Upvotes: 37