spring-security的初步应用
生活随笔
收集整理的這篇文章主要介紹了
spring-security的初步应用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
//spring-boot中的依賴<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
需要定義一個配置類 繼承自WebSecurityConfigurerAdapter,引用@EnableWebSecurity注解,讓其被spring容器托管。這里運用的是aop的思想,在不改動源代碼的情況下,為項目配置權(quán)限管理
package com.yk.config;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//鏈式編程需要注意http.authorizeRequests()//首頁 所有用戶都能訪問.antMatchers("/").permitAll()// /level1/** 只有具有vip1權(quán)限的用戶才能訪問.antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3").and().formLogin();.and()//注銷,并且重定向到指定頁面.logout().logoutSuccessUrl("/");}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//涉及到密碼之類的操作需要對其進行轉(zhuǎn)碼這里用的是BCryptPasswordEncoderauth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//為用戶admin授權(quán).withUser("admin").password(new BCryptPasswordEncoder().encode("111")).roles("vip1");} }總結(jié)
以上是生活随笔為你收集整理的spring-security的初步应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自定义一个springboot启动器
- 下一篇: 进行权限控制