[英]Spring security Oauth 2 with ajax login and form login
开发需要REST身份验证和表单登录的应用程序。 当前带有ajax登录的spring security oauth 2可以使用。 在随后的请求中可以发送“授权承载”,并且服务器成功地授权了该请求。
登录/登录的Ajax代码
function signIn() {
$.ajax({
type : 'POST',
url : 'oauth/token',
data : {
'client_id' : 'XXXXX',
'client_secret' : 'YYYYYY',
'grant_type' : 'password',
'username' :encodeURIComponent($('#login').val()),
'password' : encodeURIComponent($('#password').val()),
'scope' : 'read write'
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode("XXXXX" + ':' + "YYYYYY") )
},
success : function(response) {
var expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
response.expires_at = expiredAt.getTime();
localStorage.setItem('ls.token', JSON.stringify(response));
$.cookie("Authorization", "Bearer " + JSON.parse(localStorage.getItem("ls.token")).access_token );
var link = /*[[@{/}]]*/;
$(location).attr('href',link);
}
});
}
在随后的AJAX请求中,授权包括为
$.ajax({
url: 'api/ZZZZZ/',
type: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + JSON.parse(localStorage.getItem("ls.token")).access_token )
},
success: function(data) {}
在进行AJAX调用时,我可以在请求标头中看到授权承载
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Authorization Bearer 49ef5d34-88a2-4e20-bd7a-87042c6a62b4
Cache-Control max-age=0
Connection keep-alive
Host localhost:8080
Referer http://localhost:8080/productview?productId=19
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0
X-Requested-With XMLHttpRequest
我的春季安全配置看起来像
package com.geekyworks.equip.wowperks.config;
import javax.inject.Inject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/scripts/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/assets/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/account/reset_password/init")
.antMatchers("/api/account/reset_password/finish")
.antMatchers("/api/home/**")
.antMatchers("/api/product/**")
.antMatchers("/test/**")
.antMatchers("/devadmin/**")
.antMatchers("/signin")
.antMatchers("/static/api-guide.html");
}
@Order(67) // LOWEST
@Configuration
public static class NoAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.anyRequest()
.permitAll();
}
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
对于所有正常的http请求,即使登录后,我也总是将spring用户作为“ anonymousUser”使用。
普通的HTTP请求标头(非AJAX)在请求标头中不包括授权承载
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Cookie Authorization=Bearer%2049ef5d34-88a2-4e20-bd7a-87042c6a62b4
Host localhost:8080
Referer http://localhost:8080/
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0
相反,它包含授权载体作为Cookie信息。 我在AJAX登录后添加了cookie信息。
知道如何在单个应用程序中使用spring security oauth使FORM和AJAX身份验证同时工作吗?
Spring Security管理基于表单的身份验证的方式完全不同于您尝试通过oauth2.0实现的方式。 当您使用ajax(oauth2.0)身份验证方式(实际上是具有用户名和密码的用户对客户端应用程序的授权过程)时,只有客户端应用程序(通过其触发ajax请求的应用程序)才能通过spring进行身份验证安全筛选器和SecurityContextHolder将具有经过身份验证的客户端应用程序而不是用户的身份验证对象。 如果您将看到安全性配置,那么在非ajax登录的情况下,您将允许所有请求都通过而不进行身份验证。 要启用基于表单的登录,您需要配置安全性以保护除登录URL外的所有其他URL ...如下所示
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/**")
.authenticated().and().formLogin();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.