问题描述
我知道这个问题已经回答了很多次了,但我很困惑.我的应用程序中已经有一个身份验证机制,我只想使用 Spring MVC 的授权部分.我使用的是 Spring MVC 3 和 Spring Security 3.
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.
当我在互联网上搜索时,我发现了两个解决方案,第一个是仅实现 AuthenticationProvider 接口.示例 1.第二个是实现UserDetails和UserDetailsService,Example2 所以我迷路了.
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.
----更新----
问题的第二部分是此处.以及解决方法.
The second part of the Question is here. And the solution to the workaround.
推荐答案
在大多数情况下,当只使用用户名和密码进行身份验证和角色进行授权时,实现自己的 UserDetailsService 就足够了.
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:
- Spring 安全过滤器(基本身份验证/表单/..)获取用户名和密码,将其转换为 UsernamePasswordAuthentication 对象并将其传递给 AuthenticationManager
- 身份验证管理器寻找可以处理 UsernamePasswordtokens 的候选提供程序,在本例中是 DaoAuthenticationProvider 并传递令牌以进行身份验证
- 身份验证提供程序调用方法 loadUserByUsername 接口并在用户不存在时抛出 UsernameNotFound 异常或返回包含用户名、密码和权限的 UserDetails 对象.
- 身份验证提供程序然后比较提供的 UsernamePasswordToken 和 UserDetails 对象的密码.(它还可以通过 PasswordEncoders 处理密码哈希)如果不匹配,则身份验证失败.如果匹配,则注册用户详细信息对象并将其传递给执行授权部分的 AccessDecisionManager.
所以如果 DaoAuthenticationProvider 中的验证适合您的需求.然后你只需要实现你自己的 UserDetailsService 并调整 DaoAuthenticationProvider 的验证.
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.
使用 spring 3.1 的 UserDetailsService 示例如下:
An example for the UserDetailsService using spring 3.1 is as follows:
Spring XML:
Spring XML:
<security:authentication-manager>
<security:authentication-provider user-service-ref="myUserDetailsService" />
</security:authentication-manager>
<bean name="myUserDetailsService" class="x.y.MyUserDetailsService" />
UserDetailsService 实现:
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);
}
}
这篇关于如何在 Spring Security 3 中实现自定义身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!