How to adding new user to Spring Security in runtime
I just start programming with Spring Security, and I written system where I save users in table persisting via Hibernate. Using Spring Security reference I wrote this chunk of code:
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
You probably want to store your users in a database and not in memory, if they are registering :)
Create the authorities for the user
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
Instantiate the user (with a class implementing UserDetails)
UserDetails user = new User("user@example.com", passwordEncoder.encode("s3cr3t"), authorities);
Save the user somewhere useful. The JdbcUserDetailsManager can save a user to a database easily.
userDetailsManager.createUser(user);
Create a UsernamePasswordAuthenticationToken
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
Add the Authentication to the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
使用此代码为当前用户添加权限:
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)
);
链接地址: http://www.djcxy.com/p/28594.html
上一篇: 在中点html / css断线