springboot~security中自定义forbidden和unauthorized返回值

对于spring-security来说,当你访问一个受保护资源时,需要检查你的token,当没有传递,或者传递的token有错误时,将出现401unauthorized异常;当你传递的token是有效的,但解析后并没有访问这个资源的权限时,将返回403forbidden的异常,而你通过拦截器@RestControllerAdvice是不能重写这两个异常消息的,我们下面介绍重写这两种消息的方法。

两个接口

  • AccessDeniedHandler 实现重写403的消息
  • AuthenticationEntryPoint 实现重写401的消息

代码

  • CustomAccessDeineHandler
public class CustomAccessDeineHandler implements AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
                     AccessDeniedException accessDeniedException) throws IOException, ServletException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().print(JSONObject.toJSONString(CommonResult.forbiddenFailure("没有访问权限!")));
  }

}
  • CustomAuthenticationEntryPoint
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
                       AuthenticationException authException) throws IOException, ServletException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().print(JSONObject.toJSONString(CommonResult.unauthorizedFailure("需要先认证才能访问!")));
  }

}
  • WebSecurityConfig.configure中添加注入代码
  // 401和403自定义
  http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
      .accessDeniedHandler(new CustomAccessDeineHandler());
  • 效果
//没有传token,或者token不合法
{
    "code": 401,
    "message": "需要先认证才能访问!"
}
//token中没有权限
{
    "code": 403,
    "message": "没有访问权限!"
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
一:RestApi接口增加JWT认证功能<br/> 用户填入用户名密码后,与数据库里存储的用户信息进行比对,如果通过,则认证成功。传统的方法是在认证通过后,创建sesstion,并给客户端返回cookie。 现在我们采用JWT来处理用户名密码的认证。区别在于,认证通过后,服务器生成一个token,将token返回给客户端,客户端以后的所有请求都需要在http头指定该token。 服务器接收的请求后,会对token的合法性进行验证。验证的内容包括: 内容是一个正确的JWT格式 检查签名 检查claims 检查权限 处理登录 创建一个类JWTLoginFilter,核心功能是在验证用户名密码正确后,生成一个token,并将token返回给客户端: 该类继承自UsernamePasswordAuthenticationFilter,重写了其的2个方法: attemptAuthentication :接收并解析用户凭证。 successfulAuthentication :用户成功登录后,这个方法会被调用,我们在这个方法里生成token。 二:授权验证 用户一旦登录成功后,会拿到token,后续的请求都会带着这个token,服务端会验证token的合法性。 创建JwtAuthenticationFilter类,我们在这个类实现token的校验功能。 该类继承自BasicAuthenticationFilter,在doFilterInternal方法,从http头的Authorization 项读取token数据,然后用Jwts包提供的方法校验token的合法性。 如果校验通过,就认为这是一个取得授权的合法请求。 三:SpringSecurity配置 通过SpringSecurity的配置,将上面的方法组合在一起。 这是标准的SpringSecurity配置内容,就不在详细说明。注意其的 .addFilter(new JWTLoginFilter(authenticationManager())) .addFilter(new JwtAuthenticationFilter(authenticationManager())) 这两行,将我们定义的JWT方法加入SpringSecurity的处理流程。 四:简单测试 下面对我们的程序进行简单的验证:<br/> 1.请求获取用户列表接口:http://localhost:8080/users/userList接口,会收到403错误<br/> { "timestamp": 1518333248079, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "http://localhost:8080/users/userList" } curl http://localhost:8080/users/userList<br/> 原因就是因为这个url没有授权,所以返回403<br/> ![输入图片说明](https://gitee.com/uploads/images/2018/0211/154022_8d9806ae_130820.png "jwt-1.png") 2.注册一个新用户<br/> curl -H "Content-Type: application/json" -X POST -d '{<br/> "username": "admin",<br/> "password": "password"<br/> }' http://localhost:8080/users/signup<br/> ![输入图片说明](https://gitee.com/uploads/images/2018/0211/154042_74fb2aa6_130820.png "jwt-2.png") 3.登录,会返回token,在http header,Authorization: Bearer 后面的部分就是token<br/> curl -i -H "Content-Type: application/json" -X POST -d '{<br/> "username": "admin",<br/> "password": "password"<br/> }' http://localhost:8080/login<br/> 温馨提醒:这里的login方法是spring specurity框架提供的默认登录url ![输入图片说明](https://gitee.com/uploads/images/2018/0211/154308_9576ce90_130820.png "jwt-3.png") 4.用登录成功后拿到的token再次请求/users/userList接口<br/> 4.1将请求的XXXXXX替换成拿到的token<br/> 4.2这次可以成功调用接口了<br/> curl -H "Content-Type: application/json"<br/> -H "Authorization: Bearer XXXXXX"<br/> "http://localhost:8080/users/userList" ![输入图片说明](https://gitee.com/uploads/images/2018/0211/154315_241cd6b2_130820.png "jwt-4.png")
Spring Security 6自定义权限过滤器的步骤如下: 1.创建一个类并实现`org.springframework.web.filter.OncePerRequestFilter`接口。 2.覆盖`doFilterInternal`方法,该方法接收`HttpServletRequest`和`HttpServletResponse`对象作为参数,并在其编写自定义过滤器的逻辑。 3.使用`@Component`注释将自定义过滤器类标记为Spring组件。 4.在Spring Security配置类使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链。 下面是一个示例代码,演示如何在Spring Security 6创建自定义权限过滤器: ```java import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Component public class CustomAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 在这里编写自定义过滤器的逻辑 // 检查用户是否有足够的权限访问请求的资源 // 如果没有权限,可以返回HTTP 403 Forbidden响应 // 如果有权限,可以继续处理请求 filterChain.doFilter(request, response); } } ``` 在Spring Security配置类添加以下代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; 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.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthorizationFilter customAuthorizationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(customAuthorizationFilter, UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } } ``` 在上面的示例,我们创建了一个名为`CustomAuthorizationFilter`的自定义过滤器,并将其添加到Spring Security的过滤器链。在Spring Security配置类,我们使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链,并使用`authorizeRequests()`方法配置了请求的授权规则。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野生的狒狒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值