Spring安全Oauth 2使用ajax登录和表单登录

时间:2015-11-24 06:16:02

标签: java spring login spring-security oauth-2.0

开发需要REST身份验证以及表单登录的应用程序。目前Spring安全oauth 2使用ajax登录工作。在随后的请求中可以发送授权承载'和服务器成功授权请求。

登录/登录的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

我的Spring安全配置如下所示

  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用户称为“匿名用户”。甚至在登录后。

正常的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身份验证同时工作?

1 个答案:

答案 0 :(得分:0)

Spring安全管理基于表单的身份验证的方式完全不同于您尝试通过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();
    }
相关问题