支持跨域调用及登录功能完善

This commit is contained in:
zhh
2018-05-14 13:47:16 +08:00
parent eb667afd0a
commit 2f52c6b858
68 changed files with 125 additions and 34526 deletions

View File

@@ -0,0 +1,27 @@
package com.macro.mall.component;
import com.macro.mall.dto.CommonResult;
import com.macro.mall.util.JsonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 当未登录或者token失效访问接口时自定义的返回结果
* Created by macro on 2018/5/14.
*/
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JsonUtil.objectToJson(new CommonResult().unauthorized(authException.getMessage())));
response.getWriter().flush();
}
}

View File

@@ -12,7 +12,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用于Rest请求是返回自定义错误信息
* 当访问接口没有权限时,自定义的返回结果
* Created by macro on 2018/4/26.
*/
@Component
@@ -21,7 +21,9 @@ public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException e) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().println(JsonUtil.objectToJson(new CommonResult().authFailed(e.getMessage())));
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JsonUtil.objectToJson(new CommonResult().forbidden(e.getMessage())));
response.getWriter().flush();
}
}

View File

@@ -2,10 +2,12 @@ package com.macro.mall.config;
import com.macro.mall.bo.AdminUserDetails;
import com.macro.mall.component.JwtAuthenticationTokenFilter;
import com.macro.mall.component.RestAuthenticationEntryPoint;
import com.macro.mall.component.RestfulAccessDeniedHandler;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
@@ -21,6 +23,9 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
@@ -32,6 +37,10 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminService adminService;
@Autowired
private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
@@ -52,16 +61,22 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/v2/api-docs/**"
)
.permitAll()
.antMatchers("/admin/**")// 对于获取token的rest api要允许匿名访问
.antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问
.permitAll()
.antMatchers("/**")//测试时全部运行访问
.antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
.permitAll()
// .antMatchers("/**")//测试时全部运行访问
// .permitAll()
.anyRequest()// 除上面外的所有请求全部需要鉴权认证
.authenticated();
// 禁用缓存
httpSecurity.headers().cacheControl();
// 添加JWT filter
httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
//添加自定义未授权和未登录结果返回
httpSecurity.exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler)
.authenticationEntryPoint(restAuthenticationEntryPoint);
}
@Override
@@ -95,4 +110,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return new JwtAuthenticationTokenFilter();
}
/**
* 允许跨域调用的过滤器
*/
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}

View File

@@ -9,6 +9,8 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
@@ -17,6 +19,9 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
/**
* 后台用户管理
@@ -28,8 +33,12 @@ import javax.servlet.http.HttpServletRequest;
public class UmsAdminController {
@Autowired
private UmsAdminService adminService;
@Autowired
private UserDetailsService userDetailsService;
@Value("${jwt.tokenHeader}")
private String tokenHeader;
@Value("${jwt.tokenHead}")
private String tokenHead;
@ApiOperation(value = "用户注册")
@RequestMapping(value = "/register", method = RequestMethod.POST)
@@ -50,7 +59,10 @@ public class UmsAdminController {
if (token == null) {
return new CommonResult().validateFailed("用户名或密码错误");
}
return new CommonResult().success(token);
Map<String,String> tokenMap = new HashMap<>();
tokenMap.put("token",token);
tokenMap.put("tokenHead",tokenHead);
return new CommonResult().success(tokenMap);
}
@ApiOperation(value = "刷新token")
@@ -62,6 +74,28 @@ public class UmsAdminController {
if (refreshToken == null) {
return new CommonResult().failed();
}
return new CommonResult().success(token);
Map<String,String> tokenMap = new HashMap<>();
tokenMap.put("token",token);
tokenMap.put("tokenHead",tokenHead);
return new CommonResult().success(tokenMap);
}
@ApiOperation(value = "获取用户信息")
@RequestMapping(value = "/info",method = RequestMethod.GET)
@ResponseBody
public Object getAdminInfo(Principal principal){
String username = principal.getName();
UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
Map<String,Object> data = new HashMap<>();
data.put("username",umsAdmin.getUsername());
data.put("roles",new String[]{"TEST"});
data.put("icon",umsAdmin.getIcon());
return new CommonResult().success(data);
}
@ApiOperation(value = "登出功能")
@RequestMapping(value = "/logout",method = RequestMethod.POST)
@ResponseBody
public Object logout(){
return new CommonResult().success(null);
}
}

View File

@@ -14,13 +14,15 @@ import java.util.Map;
*/
public class CommonResult {
//操作成功
public static final int SUCCESS = 0;
public static final int SUCCESS = 200;
//操作失败
public static final int FAILED = 1;
public static final int FAILED = 500;
//参数校验失败
public static final int VALIDATE_FAILED = 2;
//认证失败
public static final int AUTHENTICATE_FAILED = 3;
public static final int VALIDATE_FAILED = 404;
//认证
public static final int UNAUTHORIZED = 401;
//未授权
public static final int FORBIDDEN = 403;
private int code;
private String message;
private Object data;
@@ -75,13 +77,25 @@ public class CommonResult {
}
/**
* 参数验证失败使用
* 未登录时使用
*
* @param message 错误信息
*/
public CommonResult authFailed(String message) {
this.code = AUTHENTICATE_FAILED;
this.message = "认证失败";
public CommonResult unauthorized(String message) {
this.code = UNAUTHORIZED;
this.message = "暂未登录或token已经过期";
this.data = message;
return this;
}
/**
* 未授权时使用
*
* @param message 错误信息
*/
public CommonResult forbidden(String message) {
this.code = FORBIDDEN;
this.message = "没有相关权限";
this.data = message;
return this;
}