Download here: http://gg.gg/o9jkk
I get the below error when I try to implement Spring security -Spring Security Httprequestmethodnotsupportedexception Request Method ’post’ Not Supported
HTTP Status 405 - Request method ’POST’ not supported ` I gave POST method on both ftl and controller. Then why would this happen? Java spring spring-mvc spring-security this question edited Dec 3 ’14 at 10:55 asked Dec 3 ’14 at 10:34 rohi 145 1 1 15 Which Spring version are you using? Spring Security 3.2+ provides support for setting X-Frame-Options on every response. By default the Spring Security Java config sets it to DENY. In 3.2 the Spring Security XML namespace does not set that header by default but may be configured to do so, and in the future it may set it by default. See Section 7.1. First of all csrf is enabled by default in Spring as of Spring 4.0 so there no need to explicitly enable it yourself. Secondly, there is no endpoint for you to authenticate your login. What you’re doing is sending a request to /login which only takes a GET request. You could create another controller method to receive that POST request and authenticate or you could use a UserDetailsService.Request Method ’post’ Not Supported Spring Security 4
Getting below issue when I am using spring-security-oauth2.jar 2.0.8.RELEASE. Same war file is working fine in other servers. Using 2.0.9.RELEASE works fine in all servers.

controller:

web.xml

Spring-security.xml

login.jsp

Error:-


09:01:22.135 [http-8080-4] DEBUG o.s.s.web.DefaultRedirectStrategy - Redirecting to ’http://localhost:8080/EmployeeManagement/login;jsessionid=E27C22793BAA2C7FC38039260EC08152’ 09:01:22.135 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 09:01:22.136 [http-8080-4] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 09:01:22.145 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 1 of 11 in additional filter chain; firing Filter: ’SecurityContextPersistenceFilter’ 09:01:22.145 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 09:01:22.145 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@48842f5e. A new one will be created. 09:01:22.145 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 2 of 11 in additional filter chain; firing Filter: ’CsrfFilter’ 09:01:22.146 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 3 of 11 in additional filter chain; firing Filter: ’LogoutFilter’ 09:01:22.146 [http-8080-4] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request ’GET /login’ doesn’t match ’POST /j_spring_security_logout 09:01:22.146 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 4 of 11 in additional filter chain; firing Filter: ’UsernamePasswordAuthenticationFilter’ 09:01:22.146 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 5 of 11 in additional filter chain; firing Filter: ’BasicAuthenticationFilter’ 09:01:22.146 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 6 of 11 in additional filter chain; firing Filter: ’RequestCacheAwareFilter’ 09:01:22.146 [http-8080-4] DEBUG o.s.s.w.s.DefaultSavedRequest - pathInfo: both null (property equals) 09:01:22.147 [http-8080-4] DEBUG o.s.s.w.s.DefaultSavedRequest - queryString: both null (property equals) 09:01:22.147 [http-8080-4] DEBUG o.s.s.w.s.DefaultSavedRequest - requestURI: arg1=/EmployeeManagement/admin; arg2=/EmployeeManagement/login;jsessionid=E27C22793BAA2C7FC38039260EC08152 (property not equals) 09:01:22.147 [http-8080-4] DEBUG o.s.s.w.s.HttpSessionRequestCache - saved request doesn’t match 09:01:22.147 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 7 of 11 in additional filter chain; firing Filter: ’SecurityContextHolderAwareRequestFilter’ 09:01:22.147 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 8 of 11 in additional filter chain; firing Filter: ’AnonymousAuthenticationFilter’ 09:01:22.147 [http-8080-4] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: ’org.springframework.security.authentication.AnonymousAuthenticationToken@6fa90ed4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: E27C22793BAA2C7FC38039260EC08152; Granted Authorities: ROLE_ANONYMOUS’ 09:01:22.147 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 9 of 11 in additional filter chain; firing Filter: ’SessionManagementFilter’ 09:01:22.148 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 10 of 11 in additional filter chain; firing Filter: ’ExceptionTranslationFilter’ 09:01:22.148 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login at position 11 of 11 in additional filter chain; firing Filter: ’FilterSecurityInterceptor’ 09:01:22.148 [http-8080-4] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : ’/login’; against ’/admin**’ 09:01:22.148 [http-8080-4] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted 09:01:22.148 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /login reached end of additional filter chain; proceeding with original chain 09:01:22.148 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name ’mvc-dispatcher’ processing GET request for [/EmployeeManagement/login] 09:01:22.149 [http-8080-4] DEBUG o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapping [/login] to HandlerExecutionChain with handler [com.employeemgmt.controller.EmployeeController@18ba5047] and 1 interceptor 09:01:22.150 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/EmployeeManagement/login] is: -1 09:01:22.189 [http-8080-4] DEBUG o.s.w.b.a.s.HandlerMethodInvoker - Invoking request handler method: public org.springframework.web.servlet.ModelAndView com.employeemgmt.controller.EmployeeController.login(java.lang.String,java.lang.String,javax.servlet.http.HttpServletRequest) 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name ’login’ 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ’org.springframework.transaction.config.internalTransactionAdvisor’ 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ’org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0’ 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ’org.springframework.transaction.config.internalTransactionAdvisor’ 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ’org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0’ 09:01:22.190 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name ’login’; URL [/WEB-INF/pages/login.jsp]] in DispatcherServlet with name ’mvc-dispatcher’ 09:01:22.190 [http-8080-4] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ’requestDataValueProcessor’ 09:01:22.190 [http-8080-4] DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/pages/login.jsp] in InternalResourceView ’login’ 09:01:22.279 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 09:01:22.279 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 09:01:22.279 [http-8080-4] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally 09:01:22.280 [http-8080-4] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 09:01:23.967 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 1 of 11 in additional filter chain; firing Filter: ’SecurityContextPersistenceFilter’ 09:01:23.967 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 09:01:23.968 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@48842f5e. A new one will be created. 09:01:23.968 [http-8080-4] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 2 of 11 in additional filter chain; firing Filter: ’CsrfFilter’ 09:01:23.969 [http-8080-4] DEBUG o.s.security.web.csrf.CsrfFilter - Invalid CSRF token found for http://localhost:8080/EmployeeManagement/j_spring_security_check 09:01:23.971 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name ’mvc-dispatcher’ processing POST request for [/EmployeeManagement/403] 09:01:23.971 [http-8080-4] DEBUG o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapping [/403] to HandlerExecutionChain with handler [com.employeemgmt.controller.EmployeeController@18ba5047] and 1 interceptor 09:01:23.982 [http-8080-4] DEBUG o.s.w.s.m.a.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@18ba5047]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method ’POST’ not supported 09:01:23.984 [http-8080-4] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@18ba5047]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method ’POST’ not supported 09:01:23.984 [http-8080-4] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@18ba5047]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method ’POST’ not supported 09:01:23.984 [http-8080-4] WARN o.s.web.servlet.PageNotFound - Request method ’POST’ not supported 09:01:23.984 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 09:01:23.984 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name ’mvc-dispatcher’: assuming HandlerAdapter completed request handling 09:01:23.984 [http-8080-4] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 09:01:23.984 [http-8080-4] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 09:01:23.984 [http-8080-4] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed


If you’ve never heard of JWTs (JSON Web Tokens), well, you don’t work in tech, or you’ve purposely unplugged your computer from the Internet. JWTs are frequently used in OAuth2 as access and refresh tokens as well as a variety of other applications.
JWTs can be used wherever you need a stand-in to represent a “user” of some kind (in quotes, because the user could be another microservice). And, they’re used where you want to carry additional information beyond the value of the token itself and have that information cryptographically verifiable as security against corruption or tampering.
For more information on the background and structure of JWTs, here’s the IETF specification
The code that backs this post can be found on GitHub.Spring Security & CSRF Protection
CSRF (Cross Site Request Forgery) is a technique in which an attacker attempts to trick you into performing an action using an existing session of a different website.
Spring Security when combined with Thymeleaf templates, automatically inserts a token into all web forms as a hidden field. This token must be present on form submission, or a Java Exception is thrown. This mitigates the risk of CSRF as an external site (an attacker) would not be able to reproduce this token.
For this sample project, the following dependencies are all that’s required to get Spring Boot, Spring Security, and Thymeleaf:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency></dependencies>246810<dependency><artifactId>spring-boot-starter-thymeleaf</artifactId><dependency><artifactId>spring-boot-starter-security</artifactId></dependencies>
Here’s a simple Thymeleaf form:<!DOCTYPE html><html xmlns:th=’ http://www.thymeleaf.org’>="" <body>="" <form="" method=’post’ th:action=’@{/jwt-csrf-form}’ >="" <input="" type=’submit’ value=’Click Me!’ gt;="" </form>="">2468<html lang=’en’xmlns:th=’http://www.thymeleaf.org’><form method=’post’th:action=’@{/jwt-csrf-form}’><input type=’submit’class=’btn btn-primary’value=’Click Me!’/></body>
Notice the xmlns:th attribute in the html tag as well as th:action attribute of the form tag. It’s these attributes that triggers Spring Security to inject the CSRF protection token into the form. Here’s what that looks like:<input type=’ hidden’="" name=’_csrf’ value=’72501b07-8205-491d-ba95-ebab5cf450de’>2<input type=’hidden’name=’_csrf’value=’72501b07-8205-491d-ba95-ebab5cf450de’/>
This is what’s called a “dumb” token. Spring Security keeps a record of this token, usually in the user’s session. When the form is submitted, it compares the value of the token to what Spring Security has on record. If the token is not present or is not the right value, an Exception is thrown.
We can improve on this using a JWT in the following ways:
*Ensure that a given token can only be used once by using a nonce cache
*Set a short expiration time for added security
*Verify that the token hasn’t been tampered with using cryptographic signaturesSwitching to JWTs for CSRF Protection
The JJWT (Java JWT) library is the premier open-source Java library for working with JSON Web Tokens. It’s clean design including a fluent interface has led to over 1,000 stars on Github.
We can easily add the JJWT library to our project by dropping in the following dependency:<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>${jjwt.version}</version></dependency>246<groupId>io.jsonwebtoken</groupId><version>${jjwt.version}</version>
Spring Security makes it easy to override the default CSRF behavior. We add three components to make this happen:
*CSRF Token Repository
*CSRF Token Validator
*Spring Security ConfigurationCSRF Token Repository
Implementing the CsrfTokenRepository interface requires three methods: generateToken, saveToken, and loadToken.
Here’s our generateToken method:@Overridepublic CsrfToken generateToken(HttpServletRequest request) { String id = UUID.randomUUID().toString().replace(’ -’,="" ’);="" date="" now="new" date();="" date="" exp="new" date(now.gettime()="" +="" (1000*30));="" 30="" seconds="" string="" token="Jwts.builder()" .setid(id)="" .setissuedat(now)="" .setnotbefore(now)="" .setexpiration(exp)="" .signwith(signaturealgorithm.hs256,="" secret)="" .compact();="" return="" new="" defaultcsrftoken(’x-csrf-token’,="" ’_csrf’,="">2468101214161820publicCsrfToken generateToken(HttpServletRequest request){Stringid=UUID.randomUUID().toString().replace(’-’,’);Date exp=newDate(now.getTime()+(1000*30));// 30 seconds.setId(id).setNotBefore(now).signWith(SignatureAlgorithm.HS256,secret)returnnewDefaultCsrfToken(’X-CSRF-TOKEN’,’_csrf’,token);
Here we see the JJWT fluent interface in action. We chain all the claims settings together and call the compact terminator method to give us the final JWT string. Most importantly, this JWT will expire after 30 seconds.
The saveToken and loadToken methods do just what they say. In this example, they are saving the token to and loading the token from the user’s session.CSRF Token Validator
Spring Security will already do the “dumb” part of the CSRF check and verify that the string it has stored matches the string that’s passed in exactly. In addition, we want to leverage the the information encoded in the JWT. This is implemented as a filter.
Here’s the core of the JwtCsrfValidatorFilter:// CsrfFilter already made sure the token matched. Here, we’ ll="" make="" sure="" it’s="" not="" expiredtry="" {="" jwts.parser()="" .setsigningkeyresolver(secretservice.getsigningkeyresolver())="" .parseclaimsjws(token.gettoken());}="" catch="" (jwtexception="" e)="" {="" most="" likely="" an="" expiredjwtexception,="" but="" this="" will="" handle="" any="" request.setattribute(’exception’,="" e);="" response.setstatus(httpservletresponse.sc_bad_request);="" requestdispatcher="" dispatcher="request.getRequestDispatcher(’expired-jwt’);" dispatcher.forward(request,="">24681012// CsrfFilter already made sure the token matched. Here, we’ll make sure it’s not expiredJwts.parser().setSigningKeyResolver(secretService.getSigningKeyResolver())}catch(JwtExceptione){// most likely an ExpiredJwtException, but this will handle anyresponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);RequestDispatcher dispatcher=request.getRequestDispatcher(’expired-jwt’);}
If the JWT is parseable, processing will continue. As you can see in the catch block, if parsing the JWT fails for any reason, we forward the request to an error page. Bpm player download full version.Spring Security Configuration
The Spring Security configuration ties it all together by registering our CSRF Token Repository with Spring Security. Here’s the configure method:protected void configure(HttpSecurity http) throws Exception { http .addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() .csrfTokenRepository(jwtCsrfTokenRepository) .ignoringAntMatchers(ignoreCsrfAntMatchers) .and() .authorizeRequests() .antMatchers(’ *’)="">24681012protectedvoidconfigure(HttpSecurity http)throwsException{.addFilterAfter(newJwtCsrfValidatorFilter(),CsrfFilter.class).csrfTokenRepository(jwtCsrfTokenRepository).and().antMatchers(’/**’)}
Line 3 adds our validator filter after the default Spring Security C

https://diarynote.indered.space

コメント

お気に入り日記の更新

テーマ別日記一覧

まだテーマがありません

この日記について

日記内を検索