这是默认登陆
HelloController控制层
配置类
package com.sxt.springsecuritytest.config;
import org.springframework.context.annotation.Bean;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 配置账号验证和请求授权
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 需求lyb只能访问admin user ,张三只能访问user
*
* 授权方法
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //开启授权请求
.antMatchers("/admin/**") //控制层路径下的请求匹配
.hasRole("admin")//一个角色和admin/路径绑定
.antMatchers("/user/**") //控制层路径下的请求匹配
.hasAnyRole("admin","user") //二个角色和user/路径绑定
.anyRequest().authenticated()//其它的请求要登陆后才能访问
.and()
.formLogin().permitAll(); //登陆表单可以登陆
}
/**
* 账号密码和角色验证方法
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()//开启身份验证
.withUser("lyb")//账号
.password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi") //密码
.roles("admin") //lyb是这角色
.and()
.withUser("zhangsan")
.password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi")
.roles("user"); //zhangsan是这角色
}
/**
* 对密码进行加密与密码匹配
* @return
*/
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
需求lyb只能访问admin user ,张三只能访问user
页面输入http://localhost:8080
lyb账号登陆
http://localhost:8080/hello 访问报404没这路径请求
http://localhost:8080/admin 访问成功
http://localhost:8080/user 访问成功
zhangsan登陆
http://localhost:8080/user 访问成功
http://localhost:8080/admin 报403不具备角色
自定义请求登陆,多写了二个处理器
package com.sxt.springsecuritytest.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
* 配置账号验证和请求授权
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 授权方法
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //开启授权请求
.antMatchers("/admin/**") //控制层路径下的请求匹配
.hasRole("admin")//一个角色和admin/路径绑定
.antMatchers("/user/**") //控制层路径下的请求匹配
.hasAnyRole("admin","user") //二个角色和user/路径绑定
.anyRequest().authenticated()//其它的请求要登陆后才能访问
.and()
.formLogin()
///////////////////////////////////////////////////////
.passwordParameter("password")//自定义登陆时密码的key
.usernameParameter("username")//自定义登陆时用户名的key
.loginProcessingUrl("/doLogin") //页面输入登陆接口请求
.loginPage("/login") //登陆页面
//登录成功的处理器
.successHandler(new AuthenticationSuccessHandler() {
/**
* 登陆成功返回一段json数据
* @param request 请求
* @param response 响应
* @param authentication 身份验证
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");//响应格式
Map<String, Object> map = new HashMap<>();//保存到集合
map.put("status",200);//成功200
map.put("msg","登录成功");
map.put("obj",authentication.getPrincipal()); //获取用户信息
PrintWriter out = response.getWriter(); //获取响应流对象
out.write(new ObjectMapper().writeValueAsString(map)); //集合里值输出到页面
out.flush();//刷新
out.close();//关闭
}
})
//登陆失败的处理器
//AuthenticationException 登陆失败的异常类
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
Map<String, Object> map = new HashMap<String,Object>();
map.put("status","500");
map.put("msg","登陆失败");
PrintWriter writer = response.getWriter();
writer.write(new ObjectMapper().writeValueAsString(map));
writer.flush();
writer.close();
}
})
.permitAll()
.and()
.csrf().disable();//安全关闭posm测试
//
}
/**
* 账号密码和角色验证方法
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()//开启身份验证
.withUser("lyb")//账号
.password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi") //密码
.roles("admin") //lyb是这角色
.and()
.withUser("zhangsan")
.password("$2a$10$JJEsTA5nvH6Z9s.vl7LyqOYIcdVI3x8uooSh7.oTI3ZoDNXt.arsi")
.roles("user"); //zhangsan是这角色
}
/**
* 对密码进行加密与密码匹配
* @return
*/
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
登陆
登陆后可访问