package me.zhengjie.core.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import java.sql.Timestamp;
import java.util.*; /**
* @author jie
* @date 2018-11-23
*/
@Getter
@AllArgsConstructor
public class JwtUser implements UserDetails { @JsonIgnore
private final Long id; private final String username; @JsonIgnore
private final String password; private final String avatar; private final String email; @JsonIgnore
private final Collection<? extends GrantedAuthority> authorities; private final boolean enabled; private Timestamp createTime; @JsonIgnore
private final Date lastPasswordResetDate; @JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
} @JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
} @JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
} @JsonIgnore
@Override
public String getPassword() {
return password;
} @Override
public boolean isEnabled() {
return enabled;
} /**
* 在我们保存权限的时候加上了前缀ROLE_,因此在这里需要处理下数据
* @return
*/
public Collection getRoles() {
Set<String> roles = new LinkedHashSet<>();
for (GrantedAuthority authority : authorities) {
roles.add(authority.getAuthority().substring(5));
}
return roles;
}
}
package me.zhengjie.core.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable; @Component
public class
JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
/**
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
*/
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}
package me.zhengjie.core.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable; @Component
public class
JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
/**
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
*/
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}
package me.zhengjie.core.security;

import io.jsonwebtoken.ExpiredJwtException;
import me.zhengjie.core.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
private final String tokenHeader; public JwtAuthorizationTokenFilter(@Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, @Value("${jwt.header}") String tokenHeader) {
this.userDetailsService = userDetailsService;
this.jwtTokenUtil = jwtTokenUtil;
this.tokenHeader = tokenHeader;
} @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
logger.debug("processing authentication for '{}'", request.getRequestURL()); final String requestHeader = request.getHeader(this.tokenHeader); String username = null;
String authToken = null;
if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
authToken = requestHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(authToken);
} catch (ExpiredJwtException e) {
logger.error(e.getMessage());
}
} logger.debug("checking authentication for user '{}'", username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
logger.debug("security context was null, so authorizating user"); // It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
// the database compellingly. Again it's up to you ;)
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info("authorizated user '{}', setting security context", username);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
}
package me.zhengjie.core.service;

import me.zhengjie.common.exception.EntityNotFoundException;
import me.zhengjie.common.utils.ValidationUtil;
import me.zhengjie.core.security.JwtUser;
import me.zhengjie.system.domain.Permission;
import me.zhengjie.system.domain.Role;
import me.zhengjie.system.domain.User;
import me.zhengjie.system.repository.PermissionRepository;
import me.zhengjie.system.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; /**
* @author jie
* @date 2018-11-22
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService { @Autowired
private UserRepository userRepository; @Autowired
private PermissionRepository permissionRepository; @Override
public UserDetails loadUserByUsername(String username){ User user = null;
if(ValidationUtil.isEmail(username)){
user = userRepository.findByEmail(username);
} else {
user = userRepository.findByUsername(username);
} if (user == null) {
throw new EntityNotFoundException(User.class, "name", username);
} else {
return create(user);
}
} public UserDetails create(User user) {
return new JwtUser(
user.getId(),
user.getUsername(),
user.getPassword(),
user.getAvatar(),
user.getEmail(),
mapToGrantedAuthorities(user.getRoles(),permissionRepository),
user.getEnabled(),
user.getCreateTime(),
user.getLastPasswordResetTime()
);
} private static List<GrantedAuthority> mapToGrantedAuthorities(Set<Role> roles,PermissionRepository permissionRepository) { Set<Permission> permissions = new HashSet<>();
for (Role role : roles) {
Set<Role> roleSet = new HashSet<>();
roleSet.add(role);
permissions.addAll(permissionRepository.findByRoles(roleSet));
} return permissions.stream()
.map(permission -> new SimpleGrantedAuthority("ROLE_"+permission.getName()))
.collect(Collectors.toList());
}
}
package me.zhengjie.core.service;

import me.zhengjie.common.exception.EntityNotFoundException;
import me.zhengjie.common.utils.ValidationUtil;
import me.zhengjie.core.security.JwtUser;
import me.zhengjie.system.domain.Permission;
import me.zhengjie.system.domain.Role;
import me.zhengjie.system.domain.User;
import me.zhengjie.system.repository.PermissionRepository;
import me.zhengjie.system.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; /**
* @author jie
* @date 2018-11-22
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService { @Autowired
private UserRepository userRepository; @Autowired
private PermissionRepository permissionRepository; @Override
public UserDetails loadUserByUsername(String username){ User user = null;
if(ValidationUtil.isEmail(username)){
user = userRepository.findByEmail(username);
} else {
user = userRepository.findByUsername(username);
} if (user == null) {
throw new EntityNotFoundException(User.class, "name", username);
} else {
return create(user);
}
} public UserDetails create(User user) {
return new JwtUser(
user.getId(),
user.getUsername(),
user.getPassword(),
user.getAvatar(),
user.getEmail(),
mapToGrantedAuthorities(user.getRoles(),permissionRepository),
user.getEnabled(),
user.getCreateTime(),
user.getLastPasswordResetTime()
);
} private static List<GrantedAuthority> mapToGrantedAuthorities(Set<Role> roles,PermissionRepository permissionRepository) { Set<Permission> permissions = new HashSet<>();
for (Role role : roles) {
Set<Role> roleSet = new HashSet<>();
roleSet.add(role);
permissions.addAll(permissionRepository.findByRoles(roleSet));
} return permissions.stream()
.map(permission -> new SimpleGrantedAuthority("ROLE_"+permission.getName()))
.collect(Collectors.toList());
}
}
package me.zhengjie.core.rest;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.common.aop.log.Log;
import me.zhengjie.core.security.AuthenticationToken;
import me.zhengjie.core.security.AuthorizationUser;
import me.zhengjie.core.utils.JwtTokenUtil;
import me.zhengjie.core.security.JwtUser;
import me.zhengjie.core.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; /**
* @author jie
* @date 2018-11-23
* 授权、根据token获取用户详细信息
*/
@Slf4j
@RestController
@RequestMapping("auth")
public class AuthenticationController { @Value("${jwt.header}")
private String tokenHeader; @Autowired
private AuthenticationManager authenticationManager; @Autowired
private JwtTokenUtil jwtTokenUtil; @Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService; /**
* 登录授权
* @param authorizationUser
* @return
*/
@Log(description = "用户登录")
@PostMapping(value = "${jwt.auth.path}")
public ResponseEntity<?> authenticationLogin(@RequestBody AuthorizationUser authorizationUser){ final UserDetails userDetails = userDetailsService.loadUserByUsername(authorizationUser.getUsername()); if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(authorizationUser.getPassword()))){
throw new AccountExpiredException("密码错误");
} if(!userDetails.isEnabled()){
throw new AccountExpiredException("账号已停用,请联系管理员");
} // 生成令牌
final String token = jwtTokenUtil.generateToken(userDetails); // 返回 token
return ResponseEntity.ok(new AuthenticationToken(token));
} /**
* 获取用户信息
* @param request
* @return
*/
@GetMapping(value = "${jwt.auth.account}")
public ResponseEntity getUserInfo(HttpServletRequest request){
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(jwtTokenUtil.getUserName(request));
return ResponseEntity.ok(jwtUser);
}
}
package me.zhengjie.core.security;

import lombok.AllArgsConstructor;
import lombok.Getter;
import java.io.Serializable; /**
* @author jie
* @date 2018-11-23
* 返回token
*/
@Getter
@AllArgsConstructor
public class AuthenticationToken implements Serializable { private final String token;
}
package me.zhengjie.core.security;

import lombok.Getter;
import lombok.Setter; import javax.validation.constraints.NotBlank; /**
* @author jie
* @date 2018-11-30
*/
@Getter
@Setter
public class AuthorizationUser { @NotBlank
private String username; @NotBlank
private String password; @Override
public String toString() {
return "{username=" + username + ", password= ******}";
}
}

JwtUser JwtAuthenticationEntryPoint JwtAuthorizationTokenFilter JwtUserDetailsService AuthenticationController的更多相关文章

  1. SpringBoot+SpringSecurity+jwt整合及初体验

    原来一直使用shiro做安全框架,配置起来相当方便,正好有机会接触下SpringSecurity,学习下这个.顺道结合下jwt,把安全信息管理的问题扔给客户端, 准备 首先用的是SpringBoot, ...

  2. 轻松上手SpringBoot Security + JWT Hello World示例

    前言 在本教程中,我们将开发一个Spring Boot应用程序,该应用程序使用JWT身份验证来保护公开的REST API.在此示例中,我们将使用硬编码的用户和密码进行用户身份验证. 在下一个教程中,我 ...

  3. WebSecurityConfig

    package me.zhengjie.core.config; import me.zhengjie.core.security.JwtAuthenticationEntryPoint; impor ...

  4. springboot2.0 web 开发标准目录架构

    ├── clean-run.sh ├── logs/ 日志文件目录 │ ├── sb2-web_test_2018-06-02_0959.0.log │ └── sb2-web_test.log | ...

  5. JWT和Spring Security集成

    通常情况下,把API直接暴露出去是风险很大的, 我们一般需要对API划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户对应的API (一)JWT是什么,为什么要使用它? 互联网服务离不开 ...

  6. Spring Boot Security And JSON Web Token

    Spring Boot Security And JSON Web Token 说明 流程说明 何时生成和使用jwt,其实我们主要是token更有意义并携带一些信息 https://github.co ...

  7. Spring Boot 使用 JWT 进行身份和权限验证

    上周写了一个 适合初学者入门 Spring Security With JWT 的 Demo,这篇文章主要是对代码中涉及到的比较重要的知识点的说明. 适合初学者入门 Spring Security W ...

  8. Spring Boot Security JWT 整合实现前后端分离认证示例

    前面两章节我们介绍了 Spring Boot Security 快速入门 和 Spring Boot JWT 快速入门,本章节使用 JWT 和 Spring Boot Security 构件一个前后端 ...

  9. VerificationCodeService

    package me.zhengjie.system.domain; import lombok.AllArgsConstructor; import lombok.Data; import lomb ...

随机推荐

  1. Bugku 加密(持续更新)

    1.滴答~滴 不多说,摩斯密码解密. 2.聪明的小羊 栅栏密码解密. 3.ok Ook解密 4.这不是摩斯密码 brainfuck解码 5.简单加密 凯撒有两种编码脚本,一种是字母26内循环移位,一种 ...

  2. addlayer添加神经网络层

    def addlayer(inputs,insize,outsize,activity_function = None):    weights = tf.Variable(tf.random_nor ...

  3. 吴裕雄--天生自然MySQL学习笔记:MySQL 创建数据表

    创建MySQL数据表需要以下信息: 表名 表字段名 定义每个表字段 语法 以下为创建MySQL数据表的SQL通用语法: CREATE TABLE table_name (column_name col ...

  4. Window Jdk配置(win7/win10都可以)

    在计算机-右键属性-高级系统设置-环境标量-系统变量下进行如下配置: 1.新建->变量名:JAVA_HOME变量值:D:\Java\jdk1.6.0_12(这只是我的JDK安装路径) 2.编辑- ...

  5. 如何快速完成一份学术型PPT

    大多人都知道有模板这么个东西. 但是拿到手却不会运用,所以只得急的找人帮忙. 毕竟一套模板的素材图表和你要展示的内容,很多都太不一样. 这种情况,怎么办?下面就来告诉你.   选中一套模版后,放大看看 ...

  6. F5 BIG-IPLTM单臂组网的三种连接模式

  7. 吴裕雄--天生自然Linux操作系统:Linux 安装

    Linux 的安装,安装步骤比较繁琐,现在其实云服务器挺普遍的,价格也便宜,如果直接不想搭建,也可以直接买一台学习用用,参考各大云服务器比较:https://www.runoob.com/linux/ ...

  8. 记录华为、魅族手机无法打印 Log 日志的问题

    http://yifeng.studio/2017/02/26/android-meizu-huawei-not-log/ 实测 MEIZU PRO 6 :打开[设置]中的[开发者选项],页面底部找到 ...

  9. Cutting Sticks UVA - 10003(DP 仍有不明白的地方)

    题意:对一根长为l的木棒进行切割,给出n个切割点,每次切割的价值,等于需要切割的木头长度. 一开始理解错了,认为切割点时根据当前木条的左端点往右推算. 实际上,左端点始终是不变的一直是0,右端点一直是 ...

  10. mysql慢SQL排查之show processlist和show full processlist

    mysql排查线上数据库问题,经常会用到 show processlist和show full processlist这两条命令 processlist命令的输出结果显示了有哪些线程在运行,不仅可以查 ...