前言
粗略配置,没有测试,仅做保存
代码
package com.core.server.system.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author :qilong sun
* @date :Created in 2019/11/27 16:56
* @description:security配置
* @modified By:
* @version: V1.0$
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* web资源过滤
* @param webSecurity
* @throws Exception
*/
@Override
public void configure(WebSecurity webSecurity) throws Exception {
// web配置
webSecurity
// 忽略不需要身份验证的uri
.ignoring()
// 静态资源目录
.mvcMatchers("/css/**", "/js/**", "/img/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("zeng")
.password(passwordEncoder().encode("zeng"))
.roles();
}
/**
* 请求过滤
* @param httpSecurity
* @throws Exception
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 静态资源
/*httpSecurity.authorizeRequests()
.antMatchers("/js/**", "/css/**", "/img/**", "/login/**").permitAll();*/
// 接口权限
httpSecurity.authorizeRequests()
.antMatchers("/user/**").hasRole("USER");
// 登录
httpSecurity.authorizeRequests()
// 自定义登录页面不用验证
.antMatchers(HttpMethod.GET, "/user-login").permitAll()
// 失败跳转不用验证
.antMatchers(HttpMethod.GET, "/user-fail").permitAll()
.anyRequest().authenticated()
.and().formLogin()
// 默认登录地址
.loginPage("/toLogin")
// 自定义用户名;默认:username
.usernameParameter("user")
// 自定义用户密码;默认:passwprd
.passwordParameter("pwd")
// 默认成功页面
.defaultSuccessUrl("/hello")
// 成功重定向页面;必须支持post方法,如果不指定,会跳到login页
.successForwardUrl("http://www.baidu.com")
// 失败页面;登录失败后会重定向到此路径,一般前后端分离不会使用它
.failureUrl("/user-fail")
// 登录失败重定向(和上面二选一)
.failureForwardUrl("/login-fail");
// 退出
httpSecurity.logout()
// 退出请求地址
.logoutUrl("/logout")
// 退出成功地址
.logoutSuccessUrl("/login");
// csrf跨站请求配置...具体配置百度
httpSecurity.csrf();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
}