How to add new user to Spring Security at runtime

2019-01-22 15:14发布

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

2条回答
劫难
2楼-- · 2019-01-22 15:56

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)
        );
查看更多
萌系小妹纸
3楼-- · 2019-01-22 16:01

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);
    
查看更多
登录 后发表回答