如何在运行时向 Spring Security 添加新用户 [英] How to add new user to Spring Security at runtime

查看:81
本文介绍了如何在运行时向 Spring Security 添加新用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过 Hibernate 将用户保存在数据库表中,并使用 Spring Security 进行身份验证:

I save users in a DB table via Hibernate and I am using Spring Security to authenticate:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

这很完美,但有一点 - 用户在服务器启动期间加载.我需要编写方法 RegisterUser(User user) 在运行时将新用户添加到 Spring Security.此方法应仅关注此任务.我不知道如何开始实现此功能,因此感谢您的任何建议!;)

And this works perfectly, but there is a point - user is loaded during server start. I need to write method RegisterUser(User user) that add new user to Spring Security in runtime. This method should focus only on this task. I dont know how to start to implement this feature so thanks for any advices! ;)

Ofc 用户具有登录名、密码、角色字符串等字段...

Ofc User have fields like login, password, role string etc etc...

请不要发布 Spring MVC 的解决方案.该系统是使用 Spring Web Boost 和 Spring Security Boost 4.0.x 版本的 RESTful 应用程序

Please do not post solutions with Spring MVC. This system is RESTful app using Spring Web Boost and Spring Security Boost in version 4.0.x

推荐答案

您可能希望将用户存储在数据库中而不是内存中,如果他们正在注册 :)

You probably want to store your users in a database and not in memory, if they are registering :)

  1. 创建用户权限

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

  • 实例化用户(使用一个实现 用户详细信息)

    UserDetails user = new User("user@example.com", passwordEncoder.encode("s3cr3t"), authorities);
    

  • 将用户保存在有用的地方.JdbcUserDetailsManager 可以轻松地将用户保存到数据库中.

  • Save the user somewhere useful. The JdbcUserDetailsManager can save a user to a database easily.

    userDetailsManager.createUser(user);
    

  • 创建一个用户名密码验证令牌

    Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
    

  • 将身份验证添加到 SecurityContext

    SecurityContextHolder.getContext().setAuthentication(authentication);
    

  • 这篇关于如何在运行时向 Spring Security 添加新用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆