Spring Security的基本配置
1. 基本用法
1.1 創(chuàng)建項(xiàng)目,添加依賴
創(chuàng)建一個(gè)Spring Boot Web 項(xiàng)目,然后添加spring-boot-starter-security依賴。
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2 添加hello接口
在項(xiàng)目中添加一個(gè)簡(jiǎn)單的/hello接口,內(nèi)容如下:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "Hello";
}
}
1.3 啟動(dòng)項(xiàng)目測(cè)試
訪問/hello接口會(huì)自動(dòng)跳轉(zhuǎn)到登錄頁(yè)面,這個(gè)頁(yè)面有Spring Security提供的。
默認(rèn)的用戶名是user,默認(rèn)的登錄密碼在每次啟動(dòng)項(xiàng)目隨機(jī)生成,查看項(xiàng)目日志:
2. 配置用戶名和密碼
在application。properties中配置默認(rèn)的用戶名、密碼以及用戶角色。
spring.security.user.name=chen
spring.security.user.password=123456
spring.security.user.roles=admin
3. 基于內(nèi)存的認(rèn)證
開發(fā)者可以自定義類繼承WebSecurityConfigurerAdapter,進(jìn)而實(shí)現(xiàn)對(duì)Spring Security更多的自定義配置。例如基于內(nèi)存的認(rèn)證。
@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)方法,在該方法中配直兩個(gè)用戶,一個(gè)用戶名是adnin ,密碼123456 ,具備兩個(gè)角色 ADMIN 和 USER;另一個(gè)用戶名是chen ,密碼是123456 ,具備一個(gè)角色 USER。
4. HttpSecurity
雖然現(xiàn)在可以實(shí)現(xiàn)認(rèn)證功能,但是受保護(hù)的資源都是默認(rèn)的,而且不能根據(jù)實(shí)際情況進(jìn)行角色管理。如果要實(shí)現(xiàn)這些功能,就需要重寫WebSecurityConfigurerAdapter中的另一個(gè)方法,代碼如下:
@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();
}
}
配置完成后,接下來(lái)在Controller中添加如下接口進(jìn)行測(cè)試:
@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用戶具有訪問權(quán)限,“/user/hello”接口admin和chen用戶具有訪問權(quán)限,“/db/hello”只有root用戶具有訪問權(quán)限。
5. 登錄表單詳細(xì)配置
在前后端分離的開發(fā)方式中,前后端的數(shù)據(jù)交互通過(guò)JSON進(jìn)行,要實(shí)現(xiàn)這些功能,需要繼續(xù)完成上文配置。文章來(lái)源:http://www.zghlxwxcb.cn/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","賬戶或密碼輸入錯(cuò)誤,登錄失敗");
}else if (e instanceof DisabledException){
map.put("msg","賬戶被禁用,登錄失敗");
}else if(e instanceof AccountExpiredException){
map.put("msg","賬戶過(guò)期,登錄失敗");
}else if(e instanceof CredentialsExpiredException){
map.put("msg","密碼過(guò)期,登錄失敗");
}else {
map.put("msg","登錄失敗");
}
ObjectMapper om= new ObjectMapper();
out.write(om.writeValueAsString(map));
out.flush();
out.close();
}
})
.permitAll()
.and();
}
}
6. 注銷登錄
如果想要注銷登錄,也只需提供簡(jiǎn)單的配置即可。文章來(lái)源地址http://www.zghlxwxcb.cn/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();
到了這里,關(guān)于Spring Boot安全管理—Spring Security基本配置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!