Spring Security 和自定义身份验证提供程序

发布于 2024-12-03 09:47:23 字数 184 浏览 0 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2024-12-10 09:47:23

当然,有多种方法可以实现这一目标。
我的首选是在自定义 UserDetailsS​​ervice。唯一的方法是 loadUserByUsername,这将返回 用户详细信息。当您构建 UserDetails 时,您可以添加任何 GrantedAuthority 你想要的。

因此,首先,您将在应用程序上下文配置文件中声明自定义 UserDetailsS​​ervice

<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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文