spring security简单介绍和访问策略
spring security是spring自带的后端权限校验安全控制框架,功能完善,简单易上手。
第一步,在pom.xml加入spring security依赖:
@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {User user = userMapper.loadUserByUsername(s);if (user == null) {//避免返回null,这里返回一个不含有任何值的User对象,在后期的密码比对过程中一样会验证失败return new User();}//查询用户的角色信息,并返回存入user中List roles = rolesMapper.getRolesByUid(user.getId());user.setRoles(roles);return user;}
UserDetails接口getAuthorities方法的示例实现:
@Override
public List getAuthorities() {List authorities = new ArrayList<>();for (Role role : roles) {authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));}return authorities;}
第三步,编写配置类,设置spring security配置项
核心配置代码示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.DigestUtils;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredUserService userService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder() {@Overridepublic String encode(CharSequence charSequence) {return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());}/*** @param cs 明文* @param s 密文*/@Overridepublic boolean matches(CharSequence cs, String s) {return s.equals(DigestUtils.md5DigestAsHex(cs.toString().getBytes()));}});}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()//http.authorizeRequests()方法有很多子方法,每个子匹配器将会按照声明的顺序起作用。.antMatchers("/admin/category/all").authenticated()//authenticated()要求在执行该请求时, 必须已经登录了应用。如果用户没有认证的话,Spring Security的Filter将会捕获该请求,并将用户重定向到应用的登录页面。 .antMatchers("/admin/**", "/reg").hasRole("超级管理员")//hasRole()要求用户必须具有权限名称为超级管理员的权限才能访问.anyRequest().authenticated()// 其他的路径都是登录后即可访问.and().formLogin().loginPage("/login_page").successHandler(success()).failureHandler(fail()).permitAll()//.loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").permitAll()//.and().logout().permitAll()//.and().csrf().disable()//csrf功能默认会开启,用于防止跨站伪造请求,以后会讲,现在先禁用,否则将无法登录。.exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());//}private AuthenticationFailureHandler fail() {return new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=utf-8");PrintWriter out = httpServletResponse.getWriter();out.write("{\"status\":\"error\",\"msg\":\"登录失败\"}");out.flush();out.close();}};}private AuthenticationSuccessHandler success() {return new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=utf-8");PrintWriter out = httpServletResponse.getWriter();out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}");out.flush();out.close();}};}@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/blogimg/**", "/index.html", "/static/**");//静态资源忽略权限校验}@BeanAccessDeniedHandler getAccessDeniedHandler() {return new AccessDeniedHandler() {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {if (request.getHeader("accept").indexOf("application/json") > -1|| (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equals("XMLHttpRequest"))) {// AJAX请求,使用response发送403response.sendError(403);} else {// 非AJAX请求,跳转系统默认的403错误界面,在web.xml中配置
// response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());// 非AJAX请求,直接输出错误提示response.setStatus(HttpServletResponse.SC_FORBIDDEN);response.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();out.write("权限不足,请联系管理员!");out.flush();out.close();}}};}
}
访问策略:
access(String) 如果给定的SpEL表达式计算结果为true,就允许访问
anonymous() 允许匿名用户访问
authenticated() 允许认证的用户进行访问
denyAll() 无条件拒绝所有访问
fullyAuthenticated() 如果用户是完整认证的话(不是通过Remember-me功能认证的),就允许访问
hasAuthority(String) 如果用户具备给定权限的话就允许访问
hasAnyAuthority(String…)如果用户具备给定权限中的某一个的话,就允许访问
hasRole(String) 如果用户具备给定角色(用户组)的话,就允许访问/
hasAnyRole(String…) 如果用户具有给定角色(用户组)中的一个的话,允许访问.
hasIpAddress(String 如果请求来自给定ip地址的话,就允许访问.
not() 对其他访问结果求反.
permitAll() 无条件允许访问
rememberMe() 如果用户是通过Remember-me功能认证的,就允许访问
其他spring security配置介绍:
HttpSecurity:spring security配置的根对象,顶级对象
.authorizeRequests()配置所有请求验证,一级配置函数
.antMatchers()添加匹配规则(为了设置指定的路径访问策略),是.authorizeRequests()下的二级配置函数
.and()无意义,仅用来连接多个一级配置函数
.formLogin()用来配置登录相关的验证,一级配置函数
.loginPage()配置登录页url,用于未登录的用户访问必须登录的资源时,spring security会转发到这个配置的登录页url,是.formLogin()下的二级配置函数
.successHandler()登录成功后返回前端时要进行的处理,是.formLogin()下的二级配置函数
.failureHandler()登录失败后返回前端时要进行的处理,是.formLogin()下的二级配置函数
.loginProcessingUrl()配置post登录请求的url,是.formLogin()下的二级配置函数
.usernameParameter()配置post登录请求的用户名key,默认为username,并且spring security会内置一个用户,用户名为user,是.formLogin()下的二级配置函数
.passwordParameter()配置post登录请求的密码key,默认为password,并且spring security会内置一个用户,密码为随机生成,会打印到控制台,是.formLogin()下的二级配置函数
.logout()用来配置注销相关的配置,一级配置函数
.csrf()防止跨站伪造请求过滤器配置,默认开启,一级配置函数
.disable()禁用防止跨站伪造请求过滤器,是.csrf()下的二级配置函数
.exceptionHandling()异常时要进行的处理,一级配置函数
.accessDeniedHandler()签权失败后返回前端时要进行的处理,是.exceptionHandling()下的二级配置函数
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
