天天看點

Spring-Security完整版配置

package com.niugang.config;


import java.io.IOException;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.alibaba.fastjson.JSONObject;
@Configuration // 裡面已經包含了@Component 是以不用再上下文中在引入入了
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// spring自帶的
@Autowired
private UserDetailsService userDetailsService;
/**
* configure(HttpSecurity)方法定義了哪些URL路徑應該被保護
*/
@Override


protected void configure(HttpSecurity http) throws Exception {

       

http.authorizeRequests()// 該方法所傳回的對象的方法來配置請求級别的安全細節
.antMatchers("/login").permitAll() // 登入頁面不攔截
.antMatchers("/api/**").permitAll() // 調用api不需要攔截
.antMatchers(HttpMethod.POST, "/checkLogin").permitAll().anyRequest().authenticated()// 對于登入路徑不進行攔截
.and().formLogin()// 配置登入頁面
.loginPage("/login")// 登入頁面的通路路徑;
.loginProcessingUrl("/checkLogin")// 登入頁面下表單送出的路徑
.failureUrl("/login?paramserror=true")// 登入失敗後跳轉的路徑,為了給用戶端提示
.defaultSuccessUrl("/index")// 登入成功後預設跳轉的路徑;
.and().logout()// 使用者退出操作
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"))// 使用者退出所通路的路徑,需要使用Post方式
.permitAll().logoutSuccessUrl("/login?logout=true")/// 退出成功所通路的路徑
.and().exceptionHandling().accessDeniedPage("/403")
.and()
.csrf().disable()
.headers().frameOptions()// 允許iframe内呈現。
.sameOrigin()
.and().sessionManagement()
/*如果使用者在不登出的情況下使用使用者名進行身份驗證,并試圖對“使用者”進行身份驗證,
* 那麼第一個會話将被強制終止并發送到/login?expired頁面。
*/
  .maximumSessions(1)
  //.expiredUrl("/login?expired=true")//如果是異步請求。無法進行頁面跳轉;
    //session過期處理政策

   .expiredSessionStrategy(new SessionInformationExpiredStrategy() {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
  String header = event.getRequest().getHeader("X-Requested-With");
  System.out.println("header:"+header);
 if(header!=null&&header.equals("XMLHttpRequest")){//異步請求
    JSONObject object= new JSONObject();
    object.put("resultCode", 302);
    object.put("redirectUrl", "login?expired=true");
   //傳回嚴格的json資料
   event.getResponse().getWriter().write(object.toJSONString());
}else{
   event.getResponse().sendRedirect("/myweb/login?expired=true"); 
} 

}
});

}

       /**
* 忽略靜态資源
*/


@Override
public void configure(WebSecurity web) throws Exception {
/*
* 在springboot中忽略靜态檔案路徑,直接寫靜态檔案的檔案夾 springboot預設有靜态檔案的放置路徑,如果應用spring
* security,配置忽略路徑 不應該從springboot預設的靜态檔案開始
* 如:在本項目中,所有的js和css都放在static下,如果配置忽略路徑,則不能以static開始
* 配置成web.ignoring().antMatchers("/static/*");這樣是不起作用的
*/

web.ignoring().antMatchers("/themes/**", "/script/**");

}

        /**
* 配置自定義使用者服務
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
// .passwordEncoder(passwordEncoder());

}

/**
* 密碼加密
*/
/*
* @Bean public BCryptPasswordEncoder passwordEncoder() { return new
* BCryptPasswordEncoder(); }
*/
}
           

異步請求session過期前端處理

$(document).ajaxComplete(function(event,request, settings){
var data=request.responseText;
var jsonObject=JSON.parse(data);
if(jsonObject.resultCode!=null&&jsonObject.resultCode==302)//根據伺服器端傳回的資料判斷
   {
           window.location.href=jsonObject.redirectUrl;
   } 
 });
           

controller修改因為加了session管理

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String toLogin(ModelMap map,String paramserror ,String expired) {
if(paramserror!=null){
map.put("errorMessage", "使用者名或密碼錯誤");
}
if(expired!=null&&expired.equals("true")){
map.put("expired", "賬戶在其他地方登陸");
}
return "view/login";
}
           

這版的配置是禁用的csrf

如果要開啟csrf,如何配置參考https://blog.csdn.net/niugang0920/article/details/79825570

                                                                               微信公衆号: 

Spring-Security完整版配置

                                                                             JAVA程式猿成長之路

                          分享資源,記錄程式猿成長點滴。專注于Java,Spring,SpringBoot,SpringCloud,分布式,微服務

繼續閱讀