我正在尝试创建一个主要使用Spring访问REST API的应用程序,并尝试配置安全端 . 尝试使用此图片显示应用程序的实际结构:
-
请求可以来自任何平台"abc.com/rest_api/"
-
请求将发送到第3点或第5点 . 如果用户已通过用户名和密码进行身份验证,则将针对令牌验证请求,否则将重定向到数据库 .
-
如果必须通过数据库对用户名和密码进行身份验证,则会生成令牌并作为响应发回 .
-
之后,只有基于令牌的身份验证才有效 .
我试图创建一个基本结构,我认为必须犯一个小错误,因为它没有按预期工作 .
@Configuration
@EnableWebSecurity
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class UserDetailsSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private NSecurityContextHolder securityContextHolder;
@Autowired
private NHttpServletRequestBinder<Authentication> authenticationBinder;
public static final String DEF_USERS_BY_USERNAME_QUERY
= "SELECT user ";
public static final String GROUPS_BY_USERNAME_QUERY =
"SELECT groups by user";
public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY =
"SELECT authorities";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(getDataSourceFromJndi())
.usersByUsernameQuery(DEF_USERS_BY_USERNAME_QUERY).
authoritiesByUsernameQuery(DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY).
groupAuthoritiesByUsername(GROUPS_BY_USERNAME_QUERY);
}
private DataSource getDataSourceFromJndi() {
try {
DataSource dataSource = (DataSource) new InitialContext().lookup("DS");
return dataSource;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(getDataSourceFromJndi())
.usersByUsernameQuery(DEF_USERS_BY_USERNAME_QUERY).
authoritiesByUsernameQuery(DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY).
groupAuthoritiesByUsername(GROUPS_BY_USERNAME_QUERY);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// The http.formLogin().defaultSuccessUrl("/path/") method is required when using stateless Spring Security
// because the session cannot be used to redirect to the page that was requested while signed out. Unfortunately
// using this configuration method will cause our custom success handler (below) to be overridden with the
// default success handler. So to replicate the defaultSuccessUrl("/path/") configuration we will instead
// correctly configure and delegate to the default success handler.
final SimpleUrlAuthenticationSuccessHandler delegate = new SimpleUrlAuthenticationSuccessHandler();
delegate.setDefaultTargetUrl("/api/");
// Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
// previously existing session.
http.sessionManagement().sessionCreationPolicy(STATELESS);
// Disable the CSRF prevention because it requires the session, which of course is not available in a
// stateless application. It also greatly complicates the requirements for the sign in POST request.
http.csrf().disable();
// Viewing any page requires authentication.
http.authorizeRequests().anyRequest().authenticated();
http
.formLogin().loginPage("http://localhost/web/ui/#access/signin")
.permitAll()
// Override the sign in success handler with our stateless implementation. This will update the response
// with any headers and cookies that are required for subsequent authenticated requests.
.successHandler(new NStatelessAuthenticationSuccessHandler(authenticationBinder, delegate));
http.logout().logoutUrl("http://localhost/web/ui/#access/signin").logoutSuccessUrl("http://localhost/web/ui/#access/signin");
// Add our stateless authentication filter before the default sign in filter. The default sign in filter is
// still used for the initial sign in, but if a user is authenticated we need to acknowledge this before it is
// reached.
http.addFilterBefore(
new StatelessAuthenticationFilter(authenticationBinder, securityContextHolder),
UsernamePasswordAuthenticationFilter.class
);
}
}
我有两种类型的authenticationBinder,即TokenBased和UserNameBased .
TokenBased:
@Component
public class NXAuthTokenHttpServletRequestBinder implements NHttpServletRequestBinder<String> {
private static final String X_AUTH_TOKEN = "X-AUTH-TOKEN";
private final NTokenFactory tokenFactory;
@Autowired
public NXAuthTokenHttpServletRequestBinder(NTokenFactory tokenFactory) {
this.tokenFactory = tokenFactory;
}
@Override
public void add(HttpServletResponse response, String username) {
final String token = tokenFactory.create(username);
response.addHeader(X_AUTH_TOKEN, token);
response.addCookie(new Cookie(X_AUTH_TOKEN, token));
}
@Override
public String retrieve(HttpServletRequest request) {
final String cookieToken = findToken(request);
if (cookieToken != null) {
return tokenFactory.parseUsername(cookieToken);
}
return null;
}
private static String findToken(HttpServletRequest request) {
Enumeration<String> it = request.getHeaderNames();
while(it.hasMoreElements()){
System.out.println(it.nextElement());
}
final String headerToken = request.getHeader(X_AUTH_TOKEN);
if (headerToken != null) {
return headerToken;
}
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (X_AUTH_TOKEN.equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}
}
UserBased:
@Component
@Primary
public class NUserAuthenticationFactory implements NHttpServletRequestBinder<Authentication> {
private final NHttpServletRequestBinder<String> httpServletRequestBinder;
@Autowired
public NUserAuthenticationFactory(NHttpServletRequestBinder<String> httpServletRequestBinder) {
this.httpServletRequestBinder = httpServletRequestBinder;
}
@Override
public void add(HttpServletResponse response, Authentication authentication) {
httpServletRequestBinder.add(response, authentication.getName());
}
@Override
public UserAuthentication retrieve(HttpServletRequest request) {
final String username = httpServletRequestBinder.retrieve(request);
if (username != null) {
return new UserAuthentication(new CustomJDBCDaoImpl().loadUserByUsername(username));
}
return null;
}
}
Problem 每当我加载应用程序时,它都会进入基于UserBased的身份验证,然后尝试从令牌中获取用户名,而不是从数据库中验证它 . 但是,那时没有令牌,因为这是我从UI发出的第一个帖子请求 . 它将我重定向回相同的登录页面 .
Logs:
精细:/在附加过滤链中的位置1的12;触发过滤器:'WebAsyncManagerIntegrationFilter'罚款:/在附加过滤器链中的位置2的12;触发过滤器:'SecurityContextPersistenceFilter'罚款:/在附加过滤器链中的位置3的12;烧制过滤器:“HeaderWriterFilter”精细:未注射HSTS头,因为它没有匹配requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@a837508精细:/在额外的过滤器链12的位置4;触发过滤器:'LogoutFilter'很好:检查请求匹配:'/';对于'http:// localhost / web / ui /#access / signin'罚款:/在第5位的12位额外的过滤链中;触发过滤器:'StatelessAuthenticationFilter'罚款:/在附加过滤器链中的位置6的12;触发过滤器:'UsernamePasswordAuthenticationFilter'罚款:请求'GET /'与'POST http:// localhost / web / ui /#access / signin罚款:/在第7位的12位额外过滤链中;触发过滤器:'RequestCacheAwareFilter'罚款:/在附加过滤器链中的位置8的12;触发过滤器:'SecurityContextHolderAwareRequestFilter'罚款:/在附加过滤器链中的位置9的12;解冻过滤器:'AnonymousAuthenticationFilter'罚款:填充带有匿名令牌的SecurityContextHolder:'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6:Principal:anonymousUser;证书:[受保护];认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@957e:RemoteIpAddress:127.0.0.1; SessionId:null;授权机构:ROLE_ANONYMOUS'罚款:/在第10位的12位额外过滤链;触发过滤器:'SessionManagementFilter'很好:请求的会话ID 3e2c15a2a427bf47e51496d2a186无效 . 精细:/在附加过滤链中的11位置12;触发过滤器:'ExceptionTranslationFilter'罚款:/在12位12的额外过滤链中;触发过滤器:'FilterSecurityInterceptor'罚款:安全对象:FilterInvocation:URL:/;属性:[authenticated]罚款:以前经过身份验证:org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6:Principal:anonymousUser;证书:[受保护];认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@957e:RemoteIpAddress:127.0.0.1; SessionId:null;授权机构:ROLE_ANONYMOUS罚款:选民:org.springframework.security.web.access.expression.WebExpressionVoter@2ac71565,返回:-1好:访问被拒绝(用户是匿名的);重定向到身份验证入口点org.springframework.security.access.AccessDeniedException:拒绝访问
1 回答
Step wise solution for your problem can be..
使用spring security
UsernamePasswordAuthenticationFilter
通过用户名和密码对用户进行身份验证,并生成唯一令牌 .编写另一个自定义安全筛选器和
AuthenticationProvider
实现,以对连续请求的用户进行身份验证 .如下所示放置自定义安全过滤器
UsernamePasswordAuthenticationFilter
http.addFilterBefore(CustomTokenBasedAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
使用
AuthenticationManager
注册AuthenticationProvider
实施那就是它!
注意: - 保护其余API的更好方法是使用一些标准协议,如oauth1a,oauth2.0等.Spring提供了oauth1a和oauth2.0协议的新颖实现 .