Spring Security的基本配置
1. 基本用法
1.1 创建项目,添加依赖
创建一个Spring Boot Web 项目,然后添加spring-boot-starter-security依赖。
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2 添加hello接口
在项目中添加一个简单的/hello接口,内容如下:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "Hello";
}
}
1.3 启动项目测试
访问/hello接口会自动跳转到登录页面,这个页面有Spring Security提供的。
默认的用户名是user,默认的登录密码在每次启动项目随机生成,查看项目日志:
2. 配置用户名和密码
在application。properties中配置默认的用户名、密码以及用户角色。
spring.security.user.name=chen
spring.security.user.password=123456
spring.security.user.roles=admin
3. 基于内存的认证
开发者可以自定义类继承WebSecurityConfigurerAdapter,进而实现对Spring Security更多的自定义配置。例如基于内存的认证。
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123456").roles("ADMIN","USER")
.and()
.withUser("chen").password("123456").roles("USER");
}
}
代码解释:
- 自定义MyWebSecurityConfig继承WebSecurityConfigurerAdapter,并重写configure(AuthenticationManagerBuilder auth)方法,在该方法中配直两个用户,一个用户名是adnin ,密码123456 ,具备两个角色 ADMIN 和 USER;另一个用户名是chen ,密码是123456 ,具备一个角色 USER。
4. HttpSecurity
虽然现在可以实现认证功能,但是受保护的资源都是默认的,而且不能根据实际情况进行角色管理。如果要实现这些功能,就需要重写WebSecurityConfigurerAdapter中的另一个方法,代码如下:
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123456").roles("ADMIN","USER")
.and()
.withUser("chen").password("123456").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("ADMIN")
.antMatchers("/user/**")
.access("hasAnyRole('ADMIN','USER')")
.antMatchers("/db/**")
.access("hasRole('admin') and hasRole('DBA')")
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.permitAll()
.and()
.csrf()
.disable();
}
}
配置完成后,接下来在Controller中添加如下接口进行测试:
@RestController
public class HelloController {
@GetMapping("/admin/hello")
public String admin(){
return "hello admin";
}
@GetMapping("/user/hello")
public String user(){
return "hello user";
}
@GetMapping("db/hello")
public String dba(){
return "hello dba";
}
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
"admin/hello"接口root和admin用户具有访问权限,“/user/hello”接口admin和chen用户具有访问权限,“/db/hello”只有root用户具有访问权限。
5. 登录表单详细配置
在前后端分离的开发方式中,前后端的数据交互通过JSON进行,要实现这些功能,需要继续完成上文配置。文章来源:https://www.toymoban.com/news/detail-473939.html
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123456").roles("ADMIN","USER")
.and()
.withUser("chen").password("123456").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("ADMIN")
.antMatchers("/user/**")
.access("hasAnyRole('ADMIN','USER')")
.antMatchers("/db/**")
.access("hasRole('admin') and hasRole('DBA')")
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login_page")
.loginProcessingUrl("/login")
.usernameParameter("name")
.passwordParameter("passwd")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Object principal = authentication.getPrincipal();
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
response.setStatus(200);
HashMap<String, Object> map = new HashMap<>();
map.put("status",200);
map.put("msg",principal);
ObjectMapper om = new ObjectMapper();
out.write(om.writeValueAsString(map));
out.flush();
out.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
response.setStatus(401);
HashMap<String, Object> map = new HashMap<>();
map.put("status",401);
if(e instanceof LockedException){
map.put("msg","账户被锁定,登录失败");
}else if(e instanceof BadCredentialsException){
map.put("msg","账户或密码输入错误,登录失败");
}else if (e instanceof DisabledException){
map.put("msg","账户被禁用,登录失败");
}else if(e instanceof AccountExpiredException){
map.put("msg","账户过期,登录失败");
}else if(e instanceof CredentialsExpiredException){
map.put("msg","密码过期,登录失败");
}else {
map.put("msg","登录失败");
}
ObjectMapper om= new ObjectMapper();
out.write(om.writeValueAsString(map));
out.flush();
out.close();
}
})
.permitAll()
.and();
}
}
6. 注销登录
如果想要注销登录,也只需提供简单的配置即可。文章来源地址https://www.toymoban.com/news/detail-473939.html
.and()
.logout()
.logoutUrl("/logout")
.clearAuthentication(true)
.addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
}
})
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.sendRedirect("/login_page");
}
})
.and();
到了这里,关于Spring Boot安全管理—Spring Security基本配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!