How to add new user to Spring Security at runtime

安稳与你 提交于 2019-11-27 12:27:12

问题


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");
    }
}

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 User have fields like login, password, role string etc etc...

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


回答1:


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

  1. Create the authorities for the user

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    
  2. Instantiate the user (with a class implementing UserDetails)

    UserDetails user = new User("user@example.com", passwordEncoder.encode("s3cr3t"), authorities);
    
  3. Save the user somewhere useful. The JdbcUserDetailsManager can save a user to a database easily.

    userDetailsManager.createUser(user);
    
  4. Create a UsernamePasswordAuthenticationToken

    Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
    
  5. Add the Authentication to the SecurityContext

    SecurityContextHolder.getContext().setAuthentication(authentication);
    



回答2:


use this code to add authority to current user:

List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_NEWUSERROLE'); 
    SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
            SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
            SecurityContextHolder.getContext().getAuthentication().getCredentials(),
            authorities)
        );


来源:https://stackoverflow.com/questions/32244745/how-to-add-new-user-to-spring-security-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!