簡體   English   中英

帶有Ajax登錄和表單登錄的Spring Security Oauth 2

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM