使用Spring security 3.2在我的Spring MVC应用程序中启用CSRF。
我的spring-security.xml
<http>
<intercept-url pattern="/**/verify" requires-channel="https"/>
<intercept-url pattern="/**/login*" requires-channel="http"/>
...
...
<csrf />
</http>
尝试为请求网址中包含“verify”的请求禁用CSRF。
MySecurityConfig.java
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
private CsrfMatcher csrfRequestMatcher = new CsrfMatcher();
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);
}
class CsrfMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
if (request.getRequestURL().indexOf("verify") != -1)
return false;
else if (request.getRequestURL().indexOf("homePage") != -1)
return false;
return true;
}
}
}
Csrf过滤器验证从“verify”提交的CSRF令牌,并在我从http向https提交请求时抛出无效令牌异常(403)。如何在这种情况下禁用csrf令牌身份验证?
答案 0 :(得分:30)
我知道这不是一个直接的答案,但是人们(就像我一样)在搜索这类问题时通常不会指定spring的版本。 所以,因为spring security a method exists允许忽略一些路径:
以下内容将确保CSRF保护忽略:
http .csrf() .ignoringAntMatchers("/sockjs/**") .and() ...
答案 1 :(得分:6)
我正在使用Spring Security v4.1。经过大量的阅读和测试后,我使用xml配置禁用特定网址的crcf安全功能。
result = trapez(integrand,0,1,10)
通过上述配置,我为所有以<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<http pattern="/files/**" security="none" create-session="stateless"/>
<http>
<intercept-url pattern="/admin/**" access="hasAuthority('GenericUser')" />
<intercept-url pattern="/**" access="permitAll" />
<form-login
login-page="/login"
login-processing-url="/login"
authentication-failure-url="/login"
default-target-url="/admin/"
password-parameter="password"
username-parameter="username"
/>
<logout delete-cookies="JSESSIONID" logout-success-url="/login" logout-url="/admin/logout" />
<http-basic />
<csrf request-matcher-ref="csrfMatcher"/>
</http>
<beans:bean id="csrfMatcher" class="org.springframework.security.web.util.matcher.OrRequestMatcher">
<beans:constructor-arg>
<util:list value-type="org.springframework.security.web.util.matcher.RequestMatcher">
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="POST"/>
</beans:bean>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="PUT"/>
</beans:bean>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="DELETE"/>
</beans:bean>
</util:list>
</beans:constructor-arg>
</beans:bean>
//...
</beans:bean>
开头的网址的POST | PUT | DELETE请求启用了crcf security 。
答案 2 :(得分:5)
我希望我的回答可以帮助别人。我发现这个问题正在搜索如何在Spring Boot 中禁用特定URL的CSFR。
我使用了这里描述的解决方案: http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/
这是Spring Security配置,允许我禁用某些URL上的CSFR控件:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Build the request matcher for CSFR protection
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
// Disable CSFR protection on the following urls:
private AntPathRequestMatcher[] requestMatchers = {
new AntPathRequestMatcher("/login"),
new AntPathRequestMatcher("/logout"),
new AntPathRequestMatcher("/verify/**")
};
@Override
public boolean matches(HttpServletRequest request) {
// If the request match one url the CSFR protection will be disabled
for (AntPathRequestMatcher rm : requestMatchers) {
if (rm.matches(request)) { return false; }
}
return true;
} // method matches
}; // new RequestMatcher
// Set security configurations
http
// Disable the csrf protection on some request matches
.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.and()
// Other configurations for the http object
// ...
return;
} // method configure
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
// Authentication manager configuration
// ...
}
}
它适用于Spring Boot 1.2.2(以及Spring Security 3.2.6)。
答案 3 :(得分:1)
暂时这条简单的线条可以很方便:
linq-expressions
答案 4 :(得分:0)
使用security =&#34; none&#34;。 例如,在spring-security-config.xml中
TestB
答案 5 :(得分:0)
明确禁用特定的网址格式,并启用某些网址格式。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig {
@Configuration
@Order
public static class GeneralWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomPasswordEncoder passwordEncoder;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/rest/**").and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/home/**","/search/**","/geo/**").authenticated().and().csrf()
.and().formLogin().loginPage("/login")
.usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/error")
.and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
}
}
}
答案 6 :(得分:0)
private let webView:WKWebView = { () -> WKWebView in
let webConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
//webView.navigationDelegate = self
webView.translatesAutoresizingMaskIntoConstraints = false
return webView
}()
func update(entity: Codable) {
guard let news = entity as? NewsStream else {
print("not a news stream!")
return
}
if news.category == nil {
news.category = news.widgetType
}
//Set global news variable
self.news = news
createWebView()
}
func createWebView(){
webView.isHidden = true
if let html = news?.html, let link = news?.webLink {
if !html.isEmpty{
webView.isHidden = false
// let html2 = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"
webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
// let myURL = URL(string: "https://www.apple.com")
// let myRequest = URLRequest(url: myURL!)
// webView.load(myRequest)
webView.frame = CGRect(x: 0, y: currentYPos, width: contentView.frame.width, height: 400)
currentYPos = currentYPos + webView.frame.height
webView.backgroundColor = UIColor.green
webView.tintColor = UIColor.orange
webView.navigationDelegate = self
}
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
self.webView.frame = CGRect(x: 0,
y: self.webView.frame.origin.y,
width:self.webView.frame.width,
height: height as! CGFloat)
})
}
print("Webview Did load")
print(webView.frame)
})
}
均值
<http ...>
<csrf request-matcher-ref="csrfMatcher"/>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
...
</http>
<b:bean id="csrfMatcher"
class="AndRequestMatcher">
<b:constructor-arg value="#{T(org.springframework.security.web.csrf.CsrfFilter).DEFAULT_CSRF_MATCHER}"/>
<b:constructor-arg>
<b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
<b:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<b:constructor-arg value="/chat/**"/>
</b:bean>
</b:bean>
</b:constructor-arg>
</b:bean>
示例来自: https://docs.spring.io/spring-security/site/docs/4.1.x/reference/htmlsingle/