java EE技术体系——CLF平台API开发注意事项(3)——API安全访问控制
前言:提离职了,嗯,这么多年了,真到了提离职的时候,心情真的很复杂。好吧,离职阶段需要把一些项目中的情况说明白讲清楚,这篇博客就简单说一下在平台中对API所做的安全处理(后面讲网关还要说,这里主要讲代码结构)
一、宏观概况
第一点:系统是按照Security规范,通过实现OAuth2.0协议安全控制。
关键词理解:
JWT:JWT,JWT 在前后端分离中的应用与实践
规范:Security、JAX-RS(当前选取Jersey:Difference between JAX-RS, Restlet, Jersey, RESTEasy, and Apache CXF
Frameworks)
安全协议:OAuth2,参考:理解OAuth 2.0
其他:java自定义注解,RBAC,CONTAINER
REQUEST FILTER
二、实现说明
2.1,安全访问过滤(重要)
在讲调用流程的时候,必须有必要说自定义的安全访问注解,云图平台的伙伴们,如果要理解系统的安全控制,或者仅是为了读接下来的流程说明,这一步很重要,一定要把这部分弄明白: (这一段是JAX-RS规范很重要的内容)
首先看我们的自定义注解:
package com.dmsdbj.library.app.security; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding; @NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Secured { String[] value() default {};
}
注意里面的@NameBinding ,请阅读:Per-JAX-RS
Method Bindings 必须要明白这个@NameBinding注解是用来干嘛的!!!
再看我们的过滤器:
@Priority(Priorities.AUTHENTICATION)
@Provider
@Secured
public class JWTAuthenticationFilter implements ContainerRequestFilter { @Inject
private Logger log; @Inject
private TokenProvider tokenProvider; @Context
private HttpServletRequest request; @Context
private ResourceInfo resourceInfo; @Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String jwt = resolveToken();
if (StringUtils.isNotBlank(jwt)) {
try {
if (tokenProvider.validateToken(jwt)) {
UserAuthenticationToken authenticationToken = this.tokenProvider.getAuthentication(jwt);
if (!isAllowed(authenticationToken)) {
requestContext.setProperty("auth-failed", true);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
final SecurityContext securityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return authenticationToken::getPrincipal;
} @Override
public boolean isUserInRole(String role) {
return securityContext.isUserInRole(role);
} @Override
public boolean isSecure() {
return securityContext.isSecure();
} @Override
public String getAuthenticationScheme() {
return securityContext.getAuthenticationScheme();
}
});
}
} catch (ExpiredJwtException eje) {
log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
requestContext.setProperty("auth-failed", true);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
} } else {
log.info("No JWT token found");
requestContext.setProperty("auth-failed", true);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
} } private String resolveToken() {
String bearerToken = request.getHeader(Constants.AUTHORIZATION_HEADER);
if (StringUtils.isNotEmpty(bearerToken) && bearerToken.startsWith("Bearer ")) {
String jwt = bearerToken.substring(7, bearerToken.length());
return jwt;
}
return null;
} private boolean isAllowed(UserAuthenticationToken authenticationToken) {
Secured secured = resourceInfo.getResourceMethod().getAnnotation(Secured.class);
if (secured == null) {
secured = resourceInfo.getResourceClass().getAnnotation(Secured.class);
}
for (String role : secured.value()) {
if (!authenticationToken.getAuthorities().contains(role)) {
return false;
}
}
return true;
}
}
附:1,You can bind a filter or interceptor to a particular annotation and when that custom annotation is applied, the filter or interceptor will automatically be bound to the annotated JAX-RS method. (文章:Per-JAX-RS
Method Bindings )
2,By default, i.e. if no name binding is applied to the filter implementation class, the filter instance is applied globally, however only after the incoming request has been matched to a particular
resource by JAX-RS runtime. If there is a @NameBinding annotation applied to the filter, the filter will also be executed at the post-match request extension point, but only in case the matched resource or sub-resource method is bound to the same name-binding
annotation. (文章:CONTAINER REQUEST FILTER)
简单说来:这个本应该用于所有请求过滤的过滤器,因为加上了@Secure的注解(而@Secure注解又加上了@NameBinding注解),所以,这个过滤器仅被用于有@Secure修饰的特定类、方法! 备注:当前过滤器执行后匹配模式@Provider
2.2,正常访问流程
由上述的过滤器说明,要想请求经过安全限制的API(有@Seured修饰),必须要得到一个可用的token信息(resolveToken方法)。
所以,第一步通过登录获取票据:
服务端:
调用login方法(UserJWTController)
@Timed
@ApiOperation(value = "authenticate the credential")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK")
,
@ApiResponse(code = 401, message = "Unauthorized")})
@Path("/authenticate")
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response login(@Valid LoginDTO loginDTO) throws ServletException { UserAuthenticationToken authenticationToken = new UserAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()); try {
User user = userService.authenticate(authenticationToken);
boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
String jwt = tokenProvider.createToken(user, rememberMe);
return Response.ok(new JWTToken(jwt)).header(Constants.AUTHORIZATION_HEADER, "Bearer " + jwt).build();
} catch (AuthenticationException exception) {
return Response.status(Status.UNAUTHORIZED).header("AuthenticationException", exception.getLocalizedMessage()).build();
}
}
A:调用了userService.authenticate(authenticationToken),根据当前登录用户,查询用户信息及其角色信息;B:调用tokenProvider.createToken(user, rememberMe),为当前用户生成一个访问票据;C:将当前的票据信息存入到响应header。
客户端:
客户端接收到请求login方法后的Response,会从中提取票据token,并存入localStorage。本系统的具体代码位置:qpp/services/quth/auth.jwt.service 附:HTML
5 Web 存储
API请求:
在第一次登录获取完票据后,后续的请求,当请求的API有自定义注解@Secured时,经过过滤器,首先解析JWT判断是否拥有访问权限,再判断是否允许访问!
附:关键类TokenProvider
package com.dmsdbj.library.app.security.jwt; import com.dmsdbj.library.app.config.SecurityConfig;
import com.dmsdbj.library.app.security.UserAuthenticationToken;
import com.dmsdbj.library.entity.User;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import io.jsonwebtoken.*; public class TokenProvider { @Inject
private Logger log; private static final String AUTHORITIES_KEY = "auth"; private String secretKey; private long tokenValidityInSeconds; private long tokenValidityInSecondsForRememberMe; @Inject
private SecurityConfig securityConfig; @PostConstruct
public void init() {
this.secretKey
= securityConfig.getSecret(); this.tokenValidityInSeconds
= 1000 * securityConfig.getTokenValidityInSeconds();
this.tokenValidityInSecondsForRememberMe
= 1000 * securityConfig.getTokenValidityInSecondsForRememberMe();
} public String createToken(User user, Boolean rememberMe) {
String authorities = user.getAuthorities().stream()
.map(authority -> authority.getName())
.collect(Collectors.joining(",")); long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInSecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInSeconds);
} return Jwts.builder()
.setSubject(user.getLogin())
.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.HS512, secretKey)
.setExpiration(validity)
.compact();
} public UserAuthenticationToken getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody(); Set<String> authorities
= Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
.collect(Collectors.toSet()); return new UserAuthenticationToken(claims.getSubject(), "", authorities);
} public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
log.info("Invalid JWT signature: " + e.getMessage());
return false;
}
}
}
三、总结
关于本平台的基本安全访问控制,大概就这些内容。其实挺简单的,就是模拟了一个票据生成中心,然后使用了JWT省去了读取服务器端session的步骤,仅通过解析JWT票据进行授权。 嗯,尽可能的在说明白,如果还是不明白的话,小伙伴们及时找我交流(先做任务,不然扛把子该......)
在本项目中涉及到的类:
java EE技术体系——CLF平台API开发注意事项(3)——API安全访问控制的更多相关文章
- java EE技术体系——CLF平台API开发注意事项(4)——API生命周期治理简单说明
文档说明 截止日期:20170905,作者:何红霞,联系方式:QQ1028335395.邮箱:hehongxia626@163.com 综述 有幸加入到javaEE技术体系的研究与开发,也得益于大家的 ...
- java EE技术体系——CLF平台API开发注意事项(1)——后端开发
前言:这是一篇帮助小伙伴在本次项目中快速进入到java EE开发的一些说明,为了让同组小伙伴们开发的时候,有个清晰点的思路.昨天给大家演示分享了基本概况,但没有留下文字总结说明,预防后期有人再次问我, ...
- java EE技术体系——CLF平台API开发注意事项(2)——后端测试
前言:上篇博客说到了关于开发中的一些情况,这篇博客主要说明一些关于测试的内容. 一.宏观说明 要求:每一个API都必须经过测试. 备注:如果涉及到服务间调用(如权限和基础数据),而对方服务不可用时 ...
- [置顶] 遵循Java EE标准体系的开源GIS服务平台架构
传送门 ☞ 系统架构设计 ☞ 转载请注明 ☞ http://blog.csdn.net/leverage_1229 传送门 ☞ GoF23种设计模式 ☞ 转载请注明 ☞ http://blog.csd ...
- [置顶] 遵循Java EE标准体系的开源GIS服务平台之二:平台部署
传送门 ☞ 系统架构设计 ☞ 转载请注明 ☞ http://blog.csdn.net/leverage_1229 传送门 ☞ GoF23种设计模式 ☞ 转载请注明 ☞ http://blog.csd ...
- Spring 4 官方文档学习 Spring与Java EE技术的集成
本部分覆盖了以下内容: Chapter 28, Remoting and web services using Spring -- 使用Spring进行远程和web服务 Chapter 29, Ent ...
- 揭秘Java架构技术体系
Web应用,最常见的研发语言是Java和PHP. 后端服务,最常见的研发语言是Java和C/C++. 大数据,最常见的研发语言是Java和Python. 可以说,Java是现阶段中国互联网公司中,覆盖 ...
- CTP API开发之一:CTP API简介
官网下载CTP API 综合交易平台CTP(Comprehensive Transaction Platform)是由上海期货信息技术有限公司(上海期货交易所的全资子公司)开发的期货交易平台,CTP平 ...
- zookeeper[3] zookeeper API开发注意事项总结
如下是根据官方接口文档(http://zookeeper.apache.org/doc/r3.4.1/api/org/apache/zookeeper/ZooKeeper.html#register( ...
随机推荐
- Kail安装后的配置
安装完Kail系统后进行简单的几项配置可以让使用更方便 VMware安装Kail系统这里就不介绍了,大家可以参考这个博客:http://www.cnblogs.com/xuanhun/p/568831 ...
- 协议详解3——IP
1. 特点: 所有的TCP,UDP,ICMP,IGMP数据都以IP数据报格式传输. 提供不可靠,无连接服务. 不可靠: 不能保证IP数据报能成功到达目的.IP仅提供最好的传输服务.如果发生某种错误时 ...
- Wannafly Union Goodbye 2016-A//初识随机化~
想来想去还是把这个题写下来了.自己在补题遇到了许多问题. 给出n(n<=1e5)个点,求是否存在多于p(p>=20)×n/100的点在一条直线上... 时限20s,多组数据,暴力至少n^2 ...
- Android(java)学习笔记114:Service生命周期
1.Service的生命周期 Android中的Service(服务)与Activity不同,它是不能和用户交互,不能自己启动的,运行在后台的程序,如果我们退出应用的时候,Servic ...
- [学习笔记] SSD代码笔记 + EifficientNet backbone 练习
SSD代码笔记 + EifficientNet backbone 练习 ssd代码完全ok了,然后用最近性能和速度都非常牛的Eifficient Net做backbone设计了自己的TinySSD网络 ...
- sqlite 新建实体时出错
解决方式 手动下载 问题原因
- cocostudio的bug(1)
今天有个女同事问我一个问题,两个cocostudio的ui同时addChild到一个layer上面,高层级的ui设置visible为false,低层级的ui设置的visible设置为true,然后低层 ...
- DELL PowerEdge R620安装Windows server(你想将windows安装在何处”找不到任何本地磁盘,“找不到驱动器”)已解决!
你可能碰到过DELL服务器上安装Windows server系列系统时无法识别或找不到硬盘的问题,对于DELL PowerEdge11-14代机器的,大家可以采用DELL的Lifecycle cont ...
- vue 使用lib-flexable,px2rem 进行移动端适配 但是引入的第三方UI组件 vux 的样式缩小,解决方案
最近在写移动端项目,就想用lib-flexable,px2rem来进行适配,把px转换成rem但是也用到了第三方UI组件库vux,把这个引入发现一个问题就是vux的组件都缩小了,在网上找不到答案,最后 ...
- Lecture 3
surface models 1. The two main methods of creating surface models are interpolation and triangulatio ...