使用 SpringBoot 提供 api 的时候,我更喜欢使用 jwt 的方式来做验证。网上有会多 Spring Security 整合 jwt 的,也有 Shiro 整合 jwt 的,感觉有点复杂。这里分享一下自己在项目中的简单实现。
除了 SpringBoot 基本的依赖,需要一个生成 jwt 和序列化的包。生成 jwt 的包依赖很多,因为我项目里使用了 hutool 这个包,就只用用它了。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
定义一个 Jwt 的 sub 字段模型,存储用户:
import lombok.Data;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Data
public class JwtUser {
/**
* 用户编号
*/
private Integer id;
/**
* 用户名
*/
private String name;
/**
* 角色
*/
private String role;
/**
* 获取当前请求用户
* @return
*/
public static JwtUser getCurrentUser() {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
return (JwtUser) request.getAttribute("user");
}
}
定义一个用于请求类和方法的注解
import java.lang.annotation.*;
@Inherited
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorize {
/**
* 是否匿名可以访问
* @return
*/
boolean anonymous() default false;
/**
* 角色
* @return
*/
String[] roles() default {};
}
用于生成 jwt 和 解析 JwtUser 对象。
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.google.gson.Gson;
import com.mpyf.xapi.security.JwtUser;
import lombok.var;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class JwtTokenUtils {
public static final String SECRET = "your_secret";
public static final String ISS = "com.your.cn";
private static final int EXPIRATIONHOURS = 24; //过期时间24小时
//创建token
public static String createToken(JwtUser user) {
return createToken(user, EXPIRATIONHOURS);
}
public static String createToken(JwtUser user, int hours) {
String subJson = new Gson().toJson(user);
JWTSigner jwtSigner = JWTSignerUtil.hs512(SECRET.getBytes());
JWT jwt = JWT.create().setSigner(jwtSigner);
jwt
.setJWTId(UUID.randomUUID().toString().replace("-", ""))
.setSubject(subJson) //用户信息
.setIssuer(ISS) //签发者
//.setAudience("受众")
//.setNotBefore(new Date())
.setIssuedAt(new Date())
.setExpiresAt(new Date(System.currentTimeMillis() + hours * 3600 * 1000));
return jwt.sign();
}
public static JwtUser getUser(String token) {
if (StringHelper.isNullOrEmpty(token)) return null;
var jwt = JWTUtil.parseToken(token);
JWTSigner jwtSigner = JWTSignerUtil.hs512(SECRET.getBytes());
jwt.setSigner(jwtSigner);
if (jwt.validate(10)) {
var subJson = jwt.getPayload("sub").toString();
JwtUser user = new Gson().fromJson(subJson, JwtUser.class);
return user;
} else {
return null;
}
}
}
定义jwt的验证拦截器,从请求头获取 token 解析并验证。
import com.mpyf.xapi.helper.JwtTokenUtils;
import com.mpyf.xapi.helper.StringHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
/**
* jwt 验证拦截器
*/
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//Authorization:Bearer+空格+token
String token = request.getHeader("Authorization");
if (token != null) {
token = token.replace("Bearer ", "");
}
//处理模拟登录的jwt
if (StringHelper.isNullOrEmpty(token)) {
token = request.getParameter("jwt");
}
if (StringHelper.isNullOrEmpty(token)) {
//兼容从请求参数传token
Object jwt = request.getAttribute("jwt");
if (jwt != null) {
token = jwt.toString();
}
}
JwtUser user = JwtTokenUtils.getUser(token);
request.setAttribute("user", user);
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
Authorize authorize = h.getMethodAnnotation(Authorize.class);
if (authorize == null) {
authorize = h.getMethod().getDeclaringClass().getAnnotation(Authorize.class);
}
//如果没有Authorize或者可以匿名访问,直接返回
if (authorize != null && !authorize.anonymous()) {
{
if (user == null) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
} else if (authorize.roles() != null && authorize.roles().length > 0 &&
Arrays.stream(authorize.roles()).allMatch(s -> !s.equalsIgnoreCase(user.getRole()))) {
//没权限
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
}
}
}
return true;
}
}
在 WebMvc 配置中注册拦截器,并支持跨域请求
import com.mpyf.xapi.security.JwtAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
JwtAuthInterceptor jwtAuthInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtAuthInterceptor).addPathPatterns("/api/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
//.maxAge(3600)
.allowCredentials(true);
WebMvcConfigurer.super.addCorsMappings(registry);
}
}
@RestController
@RequestMapping("/api/test")
@Authorize(roles = {"admin", "user"})
public class TestController {
@GetMapping("admin_and_user")
public String admin_and_user(){
return "admin 和 user 角色都可以访问";
}
@GetMapping("admin_only")
@Authorize(roles = "admin") //覆盖Controller的设置
public String admin_only(){
return "只有 admin 角色可以访问";
}
@GetMapping("public_all")
@Authorize(anonymous = true)
public String public_all(){
return "匿名可以访问";
}
}
不用 Spring Security 和 Shiro ,是不是更简单呢!
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘
我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser