javascript
security放行 spirng_Spring Security配置
第一步,空Spring Boot環(huán)境。
暫時(shí)不添加了Spring Security依賴(lài)。
第二步,確保項(xiàng)目能夠正常運(yùn)行。
啟動(dòng)啟動(dòng)項(xiàng)?Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableAutoConfiguration
public class AuthorityApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorityApplication.class, args);
}
// localhost:8080/
@RequestMapping(value = "/")
public String home() {
return "這是根路徑";
}
// localhost:8080/hello
@RequestMapping(value = "/hello")
public String hello() {
return "hello";
}
}
確保Spring Boot項(xiàng)目能夠正常啟動(dòng)。
第三步,添加了Spring Security依賴(lài)。
org.springframework.bootspring-boot-starter-security
重啟Application,訪(fǎng)問(wèn)?localhost:8080/?,出現(xiàn)以下界面,自動(dòng)跳轉(zhuǎn)至?http://localhost:8080/login?,需要登錄,實(shí)現(xiàn)了認(rèn)證功能。
第四步,自定義Spring Security配置文件?SpringSecurityCustomConfig.java?。
1.實(shí)現(xiàn)對(duì)主路徑放行、其他路徑請(qǐng)求需要驗(yàn)證、注銷(xiāo)操作允許任意權(quán)限訪(fǎng)問(wèn)、表單登錄允許任意權(quán)限訪(fǎng)問(wèn)。
2.對(duì)js、css、images不做攔截。
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration//配置文件@EnableWebSecurity//打開(kāi)web支持
public class SpringSecurityCustomConfig extends WebSecurityConfigurerAdapter {@Override
protected void configure(HttpSecurity http) throws Exception {//決定那些請(qǐng)求被攔截
http.authorizeRequests()
.antMatchers("/").permitAll()//主路徑放行
.anyRequest().authenticated()//其他請(qǐng)求需經(jīng)過(guò)驗(yàn)證
.and()
.logout().permitAll()//注銷(xiāo)操作允許任意權(quán)限訪(fǎng)問(wèn)
.and()
.formLogin().permitAll();//表單登錄允許任意權(quán)限訪(fǎng)問(wèn)
http.csrf().disable();//關(guān)閉默認(rèn)的csrf認(rèn)證
}@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js'/**", "/css/**", "/images/**");//對(duì)js、css、images不做攔截
}
}
訪(fǎng)問(wèn)主路徑?http://localhost:8080/?,不需要驗(yàn)證。
訪(fǎng)問(wèn)其他路徑?http://localhost:8080/hello?,需要驗(yàn)證。出現(xiàn)以下界面,自動(dòng)跳轉(zhuǎn)至?http://localhost:8080/login
Spring Security常見(jiàn)案例
案例一:只需登錄
不希望花太多時(shí)間做登錄功能,也不希望數(shù)據(jù)庫(kù)存儲(chǔ)登錄用戶(hù)名和密碼。
自定義Spring Security配置文件?SpringSecurityCustomConfig.java ,通知系統(tǒng)在內(nèi)存中有一個(gè)用戶(hù)名為“admin”,用戶(hù)密碼為“123456”的用戶(hù),該用戶(hù)角色為“ADMIN”。
訪(fǎng)問(wèn)需要驗(yàn)證的路徑?http://localhost:8080/hello ,分別輸入錯(cuò)誤信息和正確信息。
訪(fǎng)問(wèn)?http://localhost:8080/login?logout?即可登出。
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration// 配置文件
@EnableWebSecurity// 打開(kāi)web支持
public class SpringSecurityCustomConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Spring Security提供了一套基于內(nèi)存的驗(yàn)證
auth.inMemoryAuthentication()
.withUser("admin")
.password("123456")
.roles("ADMIN");// 自定義角色
// 可以添加若干個(gè)auth.inMemoryAuthentication()
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 決定那些請(qǐng)求被攔截
http
.authorizeRequests()
.antMatchers("/").permitAll()// 主路徑放行
.anyRequest().authenticated()// 其他請(qǐng)求需經(jīng)過(guò)驗(yàn)證
.and()
.formLogin().permitAll()// 表單登錄允許任意權(quán)限訪(fǎng)問(wèn)
.and()
.logout().permitAll();// 注銷(xiāo)操作允許任意權(quán)限訪(fǎng)問(wèn)
http.csrf().disable();// 關(guān)閉默認(rèn)的csrf認(rèn)證
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js'/**", "/css/**", "/images/**");// 對(duì)js、css、images不做攔截
}
}
案例二:指定角色,權(quán)限按角色分配
自定義Spring Security配置文件?SpringSecurityCustomConfig.java ,通知系統(tǒng)在內(nèi)存中有一個(gè)用戶(hù)名為“caiji”,用戶(hù)密碼為“caiji”的用戶(hù),該用戶(hù)角色為“USER”。
訪(fǎng)問(wèn)需要驗(yàn)證的路徑?http://localhost:8080/hello
訪(fǎng)問(wèn)需要驗(yàn)證的路徑?http://localhost:8080/roleAuth?,caiji無(wú)權(quán)限訪(fǎng)問(wèn),admin可以訪(fǎng)問(wèn)
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@RestController@EnableAutoConfiguration//Spring Boot會(huì)自動(dòng)根據(jù)jar依賴(lài)自動(dòng)配置項(xiàng)目@EnableGlobalMethodSecurity(prePostEnabled = true)// 啟動(dòng)注解@PreAuthorize的作用
public class AuthorityApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorityApplication.class, args);
}// localhost:8080/
@RequestMapping(value = "/")
public String home() {return "這是根路徑";
}// localhost:8080/hello@RequestMapping(value = "/hello")
public String hello() {return "hello ADMIN";
}// localhost:8080/hello@PreAuthorize("hasRole('ROLE_ADMIN')")//RoleVote中定義需要添加前綴@RequestMapping(value = "/roleAuth")
public String roleAuth() {return "hello USER";
}
}
SpringSecurityCustomConfig.jaca@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {//Spring Security提供了一套基于內(nèi)存的驗(yàn)證
auth.inMemoryAuthentication()
.withUser("admin")
.password("123456")
.roles("ADMIN");//自定義角色//可以添加若干個(gè)auth.inMemoryAuthentication()
auth.inMemoryAuthentication().withUser("caiji").password("caiji").roles("USER");//USER用戶(hù)
}
案例三:數(shù)據(jù)庫(kù)管理用戶(hù)
新增?UserService?類(lèi),實(shí)現(xiàn)?UserDetailsService?。
UserService.java
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class UserService implements UserDetailsService {@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {returnnull;
}
}
將用戶(hù)admin、caiji放入數(shù)據(jù)庫(kù),使用UserService管理。
SpringSecurityCustomConfig.java@Autowired
private UserService userService;@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {//Spring Security提供了一套基于內(nèi)存的驗(yàn)證//auth.inMemoryAuthentication()// .withUser("admin")// .password("123456")// .roles("ADMIN");//自定義角色// //可以添加若干個(gè)auth.inMemoryAuthentication()// auth.inMemoryAuthentication().withUser("caiji").password("caiji").roles("USER");//USER用戶(hù)
auth.userDetailsService(userService);
}
自定義密碼管理驗(yàn)證,新建?PasswordCustomEncoder?類(lèi),實(shí)現(xiàn)?PasswordEncoder?接口。
Spring Security提供了許多對(duì)密碼加密的封裝類(lèi),此處以MD5加密為例。
PasswordCustomEncoder.java
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;/**
* @author tabjin* create at 2019-06-29 09:05
* @program authority* @description*/public class PasswordCustomEncoder implements PasswordEncoder {
private final static String SALT= "123456";/**
*加密方法,對(duì)原始密碼加密* @paramcharSequence* @return
*/
@Override
public String encode(CharSequence charSequence) {
Md5PasswordEncoder md5PasswordEncoder=new Md5PasswordEncoder();return md5PasswordEncoder.encodePassword(charSequence.toString(), SALT);//加密并附加123456
}/**
*匹配方法,對(duì)原始密碼和加密后密碼匹配* @paramcharSequence* @params* @return
*/
@Override
public boolean matches(CharSequence charSequence, String s) {
Md5PasswordEncoder md5PasswordEncoder=new Md5PasswordEncoder();return md5PasswordEncoder.isPasswordValid(s, charSequence.toString(), SALT);//保證鹽值和加密時(shí)一樣
}
}
回到定義認(rèn)證的類(lèi)?SpringSecurityCustomConfig.java
SpringSecurityCustomConfig.java@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {//自定義處理
auth.userDetailsService(userService).passwordEncoder(new PasswordCustomEncoder());//指定好UserService后添加自定義密碼驗(yàn)證器//Spring Security 默認(rèn)數(shù)據(jù)庫(kù)處理,表結(jié)構(gòu)位于users.ddl
auth.jdbcAuthentication().usersByUsernameQuery("").passwordEncoder(new PasswordCustomEncoder());
}
總結(jié)
以上是生活随笔為你收集整理的security放行 spirng_Spring Security配置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: # 字符串从右往左查找_字符串匹配(搜索
- 下一篇: springboot 注解动态赋值_Sp