Spring Security和自定义身份验证提供程序(Spring Security and Custom Authentication Provider)

系统教程 行业动态 更新时间:2024-06-14 17:04:02
Spring Security和自定义身份验证提供程序(Spring Security and Custom Authentication Provider)

我有一个自定义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

本文发布于:2023-04-24 20:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/296a0e975c61dd5d7bbfd7b0b6f7afd2.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   身份验证   程序   Security   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!