我有一个自定义AuthenticationProvider ,它只返回authenticate方法的Authentication对象。 我想要做的是在用户登录时为其添加一个角色。这是出于演示目的,所以我想要的是用户输入用户名并让他们进入。我需要为他们分配管理员角色。
I have a custom AuthenticationProvider that simply returns the Authentication object for the authenticate method. What I want to do is add a role to the user when they log in. This is for demo purposes, so all I want is the user to enter a username and let them in. I need to assign them the admin role.
最满意答案
当然,有几种方法可以实现这一目标。 我首选的是在自定义UserDetailsService执行此操作。 唯一的方法是loadUserByUsername ,它将返回UserDetails的实例。 在构建UserDetails ,可以添加所需的GrantedAuthority 。
首先,您将在应用程序上下文配置文件中声明自定义UserDetailsService :
<bean id="myCustomUDS" class="com.myapp.AppUDS" /> <sec:authentication-manager alias="authenticationManager"> <sec:authentication-provider user-service-ref="myCustomUDS"> </sec:authentication-provider> </sec:authentication-manager>然后你自己编写类:
public class AppUDS implements UserDetailsService { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { //create your concrete UserDetails //add your custom role (i.e. GrantedAuthority) to that object (that will be added to all users) //return it } }There are, of course, several ways to achieve that. My preferred one is do this in a custom UserDetailsService. The only method is loadUserByUsername, that will return an instance of UserDetails. When you are constructing your UserDetails, you can add whatever GrantedAuthority you want.
So first, you'll declare your custom UserDetailsService in your application context configuration file:
<bean id="myCustomUDS" class="com.myapp.AppUDS" /> <sec:authentication-manager alias="authenticationManager"> <sec:authentication-provider user-service-ref="myCustomUDS"> </sec:authentication-provider> </sec:authentication-manager>Then you write the class itself:
public class AppUDS implements UserDetailsService { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { //create your concrete UserDetails //add your custom role (i.e. GrantedAuthority) to that object (that will be added to all users) //return it } }更多推荐
角色,authenticate,电脑培训,计算机培训,IT培训"/> <meta name="description&q
发布评论