一.token的认证自定义异常
1.在资源服务器配置
2.创建CustomOAuthEntryPoint
package com.othp.core.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class CustomOAuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws ServletException {
Map map = new HashMap();
map.put("code", "40001");
map.put("message", "token无效!");
// map.put("message", authException.getMessage());
map.put("data", request.getServletPath());
response.setContentType("application/json");
//请求正常码 200
response.setStatus(HttpServletResponse.SC_OK);
// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), map);
} catch (Exception e) {
throw new ServletException();
}
}
}
3.在资源服务器的配置authenticationEntryPoint
package com.othp.mine.config;
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.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import com.othp.core.config.CustomOAuthEntryPoint;
@Configuration
@EnableResourceServer //@这个注解就决定了这是个资源服务器。
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private CustomOAuthEntryPoint customOAuthEntryPoint;
@Override
public void configure(HttpSecurity http) throws Exception {
//post请求默认的都开启了csrf的模式,所有post请求都必须带有token之类的验证信息才可以进入登陆页面,这边是禁用csrf模式
http.csrf().disable();
http.authorizeRequests() //方法有多个子节点,每个匹配器按其声明的顺序进行考虑。
.antMatchers(
//waggerui 忽略
"/webjars/**",
"/resources/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/v2/api-docs",
//系统使用
"/CK030201/*",
"/Common/getPhoneCode",
"/SJ030101/*",
"/Common/getToken")
// .antMatchers("**")
.permitAll(); //不需要认证
http.authorizeRequests()
.anyRequest()
.authenticated(); //用户进行身份验证
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
//bearer token的验证,异常自定义返回
resources.authenticationEntryPoint(customOAuthEntryPoint);
}
}
3.调用相应接口。传错误的bearer
二、token获取时,账号密码错误异常自定义
待更新。。。