日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring security之httpSecurity使用示例

發(fā)布時間:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring security之httpSecurity使用示例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

httpSecurity

? ?類似于spring security的xml配置文件命名空間配置中的<http>元素。它允許對特定的http請求基于安全考慮進(jìn)行配置。默認(rèn)情況下,適用于所有的請求,但可以使用requestMatcher(RequestMatcher)或者其它相似的方法進(jìn)行限制。

使用示例:

最基本的基于表單的配置如下。該配置將所有的url訪問權(quán)限設(shè)定為角色名稱為"ROLE_USER".同時也定義了內(nèi)存認(rèn)證模式:使用用戶名"user"和密碼“password”,角色"ROLE_USER"來認(rèn)證。

@Configuration@EnableWebSecuritypublic class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user") .password("password") .roles("USER"); } }

?配置基于openId的認(rèn)證方式

?basic示例,不使用attribute exchange

@Configuration@EnableWebSecuritypublic class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) {http.authorizeRequests().antMatchers("/").hasRole("USER").and().openidLogin().permitAll();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication()// the username must match the OpenID of the user you are// logging in with.withUser("https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU") .password("password") .roles("USER"); } }

下面展示一個更高級的示例,使用attribute exchange

@Configuration@EnableWebSecuritypublic class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) {http.authorizeRequests().antMatchers("/").hasRole("USER").and().openidLogin().loginPage("/login").permitAll().authenticationUserDetailsService(new AutoProvisioningUserDetailsService()) .attributeExchange("https://www.google.com/.") .attribute("email") .type("http://axschema.org/contact/email") .required(true) .and() .attribute("firstname") .type("http://axschema.org/namePerson/first") .required(true) .and() .attribute("lastname") .type("http://axschema.org/namePerson/last") .required(true) .and() .and() .attributeExchange(".yahoo.com.") .attribute("email") .type("http://schema.openid.net/contact/email") .required(true) .and() .attribute("fullname") .type("http://axschema.org/namePerson") .required(true) .and() .and() .attributeExchange(".myopenid.com.") .attribute("email") .type("http://schema.openid.net/contact/email") .required(true) .and() .attribute("fullname") .type("http://schema.openid.net/namePerson") .required(true); } } public class AutoProvisioningUserDetailsService implements AuthenticationUserDetailsService&lt;OpenIDAuthenticationToken&gt; { public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException { return new User(token.getName(), "NOTUSED", AuthorityUtils.createAuthorityList("ROLE_USER")); } }

增加響應(yīng)安全報文頭

默認(rèn)情況下當(dāng)使用WebSecuirtyConfigAdapter的默認(rèn)構(gòu)造函數(shù)時激活。

僅觸發(fā)Headers()方法而不觸發(fā)其它方法或者接受WebSecurityConfigureerAdater默認(rèn)的,等同于:

@Configuration@EnableWebSecuritypublic class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.headers().contentTypeOptions();.xssProtection().cacheControl().httpStrictTransportSecurity().frameOptions().and()...;}}

取消安全報文頭,如下:

@Configuration@EnableWebSecuritypublic class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.headers().disable()...;}}

使用部分安全報文頭

觸發(fā)headers()方法的返回結(jié)果,例如,只使用HeaderConfigurer的cacheControll()方法和HeadersConfigurer的frameOptions()方法.

@Configuration@EnableWebSecuritypublic class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.headers().cacheControl().frameOptions().and()...;}}

配置session管理

下面的配置展示了只允許認(rèn)證用戶在同一時間只有一個實(shí)例是如何配置的。若一個用戶使用用戶名為"user"認(rèn)證并且沒有退出,同一個名為“user”的試圖再次認(rèn)證時,第一個用戶的session將會強(qiáng)制銷毀,并設(shè)置到"/login?expired"的url。

@Configuration@EnableWebSecuritypublic class SessionManagementSecurityConfig extendsWebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().hasRole("USER").and().formLogin().permitAll().and().sessionManagement().maximumSessions(1).expiredUrl("/login?expired"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth. inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

當(dāng)使用SessionManagementConfigurer的maximumSessio(int)時不用忘記為應(yīng)用配置HttpSessionEventPublisher,這樣能保證過期的session能夠被清除。

在web.xml中可以這樣配置:

<listener><listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>;</listener>

配置PortMapper

允許配置一個從HttpSecurity的getSharedObject(Class)方法中獲取的PortMapper。當(dāng)http請求跳轉(zhuǎn)到https或者h(yuǎn)ttps請求跳轉(zhuǎn)到http請求時(例如我們和requiresChanenl一起使用時),別的提供的SecurityConfigurer對象使用P誒賬戶的PortMapper作為默認(rèn)的PortMapper。默認(rèn)情況下,spring security使用PortMapperImpl來映射http端口8080到https端口8443,并且將http端口的80映射到https的端口443.

配置示例如下,下面的配置將確保在spring security中的http請求端口9090跳轉(zhuǎn)到https端口9443 并且將http端口80跳轉(zhuǎn)到https443端口。

@Configuration@EnableWebSecuritypublic class PortMapperSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin().permitAll().and()// Example portMapper() configuration.portMapper().http(9090).mapsTo(9443) .http(80).mapsTo(443); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

配置基于容器的預(yù)認(rèn)證

在這個場景中,servlet容器管理認(rèn)證。

配置示例:

下面的配置使用HttpServletRequest中的principal,若用戶的角色是“ROLE_USER”或者"ROLE_ADMIN",將會返回Authentication結(jié)果。

   @Configuration@EnableWebSecuritypublic class JeeSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and()// Example jee() configuration.jee().mappableRoles("ROLE_USER", "ROLE_ADMIN"); } }

開發(fā)者希望使用基于容器預(yù)認(rèn)證時,需要在web.xml中配置安全限制。例如:

<login-config><auth-method>FORM</auth-method><form-login-config><form-login-page>/login</form-login-page><form-error-page>/login?error</form-error-page></form-login-config></login-config><security-role><role-name>ROLE_USER</role-name></security-role><security-constraint><web-resource-collection><web-resource-name>Public</web-resource-name><description>Matches unconstrained pages</description><url-pattern>/login</url-pattern><url-pattern>/logout</url-pattern><url-pattern>/resources/</url-pattern></web-resource-collection></security-constraint><security-constraint><web-resource-collection><web-resource-name>Secured Areas</web-resource-name><url-pattern>/</url-pattern></web-resource-collection><auth-constraint><role-name>ROLE_USER</role-name></auth-constraint></security-constraint>

配置基于X509的預(yù)認(rèn)證

配置示例,下面的配置試圖從X509證書中提取用戶名,注意,為完成這個工作,客戶端請求證書需要配置到servlet容器中。

@Configuration@EnableWebSecuritypublic class X509SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and()// Example x509() configuration.x509();}}

配置Remember-me服務(wù)

配置示例,下面的配置展示了如何允許基于token的remember-me的認(rèn)證。若http參數(shù)中包含一個名為“remember-me”的參數(shù),不管session是否過期,用戶記錄將會被記保存下來。

@Configuration@EnableWebSecuritypublic class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception {auth.inMemoryAuthentication().withUser("user").password("password") .roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").hasRole("USER") .and() .formLogin() .permitAll() .and() // Example Remember Me Configuration .rememberMe(); } }

限制HttpServletRequest的請求訪問

配置示例,最基本的示例是配置所有的url訪問都需要角色"ROLE_USER".下面的配置要求每一個url的訪問都需要認(rèn)證,并且授權(quán)訪問權(quán)限給用戶"admin"和"user".

@Configuration@EnableWebSecuritypublic class AuthorizeUrlsSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin();}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") .and() .withUser("adminr") .password("password") .roles("ADMIN","USER"); } }

同樣,也可以配置多個url。下面的配置要求以/admin/開始的url訪問權(quán)限為“admin”用戶。

@Configuration@EnableWebSecuritypublic class AuthorizeUrlsSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/**").hasRole("USER").and().formLogin();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") .and() .withUser("adminr") .password("password") .roles("ADMIN","USER"); } }

注意:匹配起效是按照順序來的。因此如果下面的配置是無效的,因?yàn)闈M足第一個規(guī)則后將不會檢查第二條規(guī)則:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**").hasRole("ADMIN")

增加CSRF支持

默認(rèn)情況下,當(dāng)使用WebSecurityConfigurerAdapter時的默認(rèn)構(gòu)造方法時CSRF是激活的。你可以使用如下方法關(guān)閉它:

@Configuration@EnableWebSecuritypublic class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable()...;}}

增加logout支持

默認(rèn)支持,當(dāng)使用WebSecurityConfigurerAdapter時Logout是支持的。當(dāng)用戶發(fā)出“/logout”請求時,系統(tǒng)將會銷毀session并且清空配置的rememberMe()認(rèn)證,然后清除SecurityContextHolder,最后跳向logout成功頁面或者登陸頁面。

@Configuration@EnableWebSecuritypublic class LogoutSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin().and()// sample logout customization.logout().logout().deleteCookies("remove") .invalidateHttpSession(false) .logoutUrl("/custom-logout") .logoutSuccessUrl("/logout-success"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

匿名用戶控制

使用WebSecurityConfigurerAdapter時自動綁定。默認(rèn)情況下,匿名用戶有一個AnonymousAuthenticationToken標(biāo)示,包含角色"ROLE_ANONYMOUS"。

下面的配置展示了如何指定匿名用戶應(yīng)該包含"ROLE_ANON".

@Configuration@EnableWebSecuritypublic class AnononymousSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin().and()// sample anonymous customization.anonymous().authorities("ROLE_ANON"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

基于表單的認(rèn)證

若FormLoginConfigurer的loginpage(String)沒有指定,將會產(chǎn)生一個默認(rèn)的login頁面。

示例配置:

@Configuration@EnableWebSecuritypublic class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

下面的示例展示了自定義的表單認(rèn)證:

@Configuration@EnableWebSecuritypublic class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").hasRole("USER").and().formLogin().usernameParameter("j_username") // default is username.passwordParameter("j_password") // default is password.loginPage("/authentication/login") // default is /login with an HTTP get.failureUrl("/authentication/login?failed") // default is /login?error.loginProcessingUrl("/authentication/login/process"); // default is /login with an HTTP post}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

配置安全通道

為使配置生效,需至少配置一個通道的映射。

配置示例:

下面例子展示了如何將每個請求都使用https通道。

@Configuration@EnableWebSecuritypublic class ChannelSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin().and().channelSecurity().anyRequest().requiresSecure();}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

配置http 基本認(rèn)證

配置示例:

@Configuration@EnableWebSecuritypublic class HttpBasicSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/**").hasRole("USER").and().httpBasic();}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

配置要觸發(fā)的HttpRequest

重寫RequestMatcher方法、antMatcher()z、regexMatcher()等。

配置示例

下面的配置使HttpSecurity接收以"/api/","/oauth/"開頭請求。

@Configuration@EnableWebSecuritypublic class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/api/**","/oauth/**").and().authorizeRequests().antMatchers("/**").hasRole("USER").and().httpBasic();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

下面的配置和上面的相同:

@Configuration@EnableWebSecuritypublic class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/api/**").antMatchers("/oauth/**").and().authorizeRequests().antMatchers("/**").hasRole("USER").and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

同樣也可以這樣使用:

@Configuration@EnableWebSecuritypublic class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/api/**").and().requestMatchers().antMatchers("/oauth/**").and().authorizeRequests().antMatchers("/**").hasRole("USER").and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); } }

?

小結(jié):

? ?本文是從httpSecurity代碼中整理得來的,有助于對spring security的全面理解。

?

轉(zhuǎn)載于:https://www.cnblogs.com/davidwang456/p/4549344.html

總結(jié)

以上是生活随笔為你收集整理的spring security之httpSecurity使用示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 肉丝美足丝袜一区二区三区四 | 国产剧情精品 | 综合成人在线 | 欧美涩涩涩 | 日韩欧美综合在线 | 天天干天天插天天操 | 黄色片网站在线免费观看 | 夫妻性生活自拍 | 亚洲综合社区 | 欧美老熟妇喷水 | а√天堂资源在线 | 亚洲精品一区二区三区影院忠贞 | 美女脱光衣服让男人捅 | 最近中文字幕在线观看 | 国产日韩视频 | 国产精品一区久久久 | 91国偷自产一区二区三区女王 | 激情五月在线 | 久久88| 国产做爰免费观看 | 白石茉莉奈中文字幕在 | 国产精品一区在线观看 | 免费欧美日韩 | 日本人性爱视频 | 色视频国产 | 国产亚洲精品美女 | 国产成人一区二区三区视频 | 91精品国产综合久久久蜜臀图片 | 国内精品小视频 | 国产又粗又猛又爽又黄91 | 性一交一乱一伧国产女士spa | 我要操av| 久久亚洲AV成人无码国产野外 | 国产一区二区三区自拍 | 中文字幕无线精品亚洲乱码一区 | 女同性恋一区二区三区 | 丰满少妇在线观看资源站 | 色戒电影未测减除版 | 精品一区李梓熙捆绑 | 欧美大肚乱孕交hd孕妇 | 国产精品高清网站 | 逼特逼视频在线观看 | 一级理论片 | 古代玷污糟蹋np高辣h文 | 日韩午夜激情电影 | 免费av网站在线观看 | 国产成人精品一区二区三区四区 | 国产亚洲综合精品 | 免费人成又黄又爽又色 | 青青青手机视频在线观看 | 成人高清在线观看 | 久久99精品久久久久子伦 | 国产精品va在线 | 国产极品探花 | 天天干,夜夜操 | 天堂网a | 日韩网站在线播放 | 91在线免费播放 | 亚洲二区av | 豆花视频在线播放 | 国产成人精品午夜福利Av免费 | 大度亲吻原声视频在线观看 | 熊出没之冬日乐翻天免费高清观看 | 大桥未久av在线播放 | 在线观看日批视频 | 夜夜操夜夜爽 | 亚洲国产婷婷香蕉久久久久久99 | 亚洲人一区二区三区 | 国产乱码精品一区二区三区亚洲人 | 亚洲一区二区精品在线观看 | 欧美狠狠干 | 美女露出让男生揉的视频 | 九九热在线精品视频 | 日本视频一区二区 | 国产福利在线播放 | 日日夜夜狠狠操 | www.久色| 99久久国 | 综合色爱 | 日韩精品专区 | 免费三片在线观看网站v888 | 超碰成人免费在线 | 黑人操亚洲人 | 射黄视频| 激情综合色 | 久久国产精品一区二区三区 | 日韩毛片中文字幕 | www.波多野结衣.com | av资源站 | 超薄肉色丝袜一区二区 | 欧美日韩在线二区 | a色网站 | 制服丝袜中文字幕在线 | 亚洲人视频在线观看 | 中日毛片 | 久久久久亚洲av无码专区喷水 | 国产精品日韩欧美大师 | 91尤物视频在线观看 | aaaaav|