I have updated Spring security from 4.x to 5.x. Now, I have this situation where Spring security asks user to confirm logout. With message
Are you sure you want to log out?
below given image for the same.
I want to get rid of this step. How to get rid of logout confirmation ?
Objective : I want to logout and redirect on page where I came from.
The security.xml :
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<http auto-config="true" use-expressions="true">
<!-- isAnonymous() -->
<intercept-url pattern="/**/add/**" access="isAuthenticated()" />
<intercept-url pattern="/**/delete/**" access="isAuthenticated()" />
<intercept-url pattern="/**/update/**" access="isAuthenticated()" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="uzer64" password="{noop}123456" authorities="ROLE_USER" />
<user name="admin" password="{noop}admin" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
It is a CSRF feature to avoid logout request initiated by malicious javascript from another site.
Your request is GET: /logout and hence spring security wants to confirm it by user action such as click.
So to avoid it. Your logout request should be POST and contain valid _csrf token.
You can achieve it by using spring form tag with method post as given below
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
...
<form:form action="${pageContext.request.contextPath}/logout"
method="post" modelAttribute="AnyModelAttributePassedFromController">
<form:button value="submit"> Logout</form:button>
</form:form>
...
Or
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
...
<form:form action="${pageContext.request.contextPath}/logout"
method="post" modelAttribute="_csrf">
<form:button value="submit"> Logout</form:button>
</form:form>
...
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
It works for me.
You can try the below:-
<logout
logout-success-url="/anonymous.html"
logout-url="/perform_logout" />
and you can mention the url where you want to redirect.You can also add
delete-cookies="JSESSIONID" for deleting cookies.
Related
So I have this in my spring config xml file.
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/welcome/*" access="hasRole('ADMIN')" />
<!-- <intercept-url pattern="/login" requires-channel="https" /> -->
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="emailId"
password-parameter="pwd" />
<logout logout-success-url="/login?logout"/>
</http>
The role is authenticated correctly at login. I have 2 questions:
What's the difference between pattern="/welcome/*", pattern="/welcome*" and pattern="/welcome/**"? When the pattern="/welcome/*", the login is successful and the user sees the page. In both the other options, the 403 Access Denied page appears. The user does have 'ADMIN' privileges)
How does Spring security process logout? I have the following code in my welcome.jsp file:
<c:url value="/logout" var="logoutUrl" />
<form action="${logoutUrl}" method="GET" id="logoutForm">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
<script>
function formSubmit() {
document.getElementById("logoutForm").submit();
}
</script>
<c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>
User : ${pageContext.request.userPrincipal.name} | Logout
</h2>
</c:if>
and this in my controller:
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
The page redirects correctly and displays the "logout successful" page but if I change the URL to go to "/welcome" again, it shows me the page. Shouldn't it display the 403 - Access Denied page?
About Ant Path matchers in Spring Security
The main role of using Ant-style syntax that you've mentioned is to resolve what exactly paths are valid.
The mapping matches URLs using the following rules:
? matches one character
* matches zero or more characters
** matches zero or more directories in a path
Regarding your cases:
/welcome/* - this could be valid for URLs like /welcome/hello or /welcome/#hello, /welcome/?abc=123
/welcome* - valid are /welcome?abc=123, /welcome#abc=123.
/welcome/** - valid case is /welcome/hello/bye?abc=123.
More on this could be found at Spring Documentation.
Logout action
I assume that you are using xml-configuration for security. Anyway this could be modified for usage of pure Java-configuration.
In app-security.xml should be something like this below:
<http use-expressions="true"
disable-url-rewriting="true">
<http-basic />
<!-- other configurations -->
<intercept-url pattern="/login**" access="isAnonymous()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<!-- other configurations -->
<logout logout-url="/logout"
logout-success-url="/login"/>
</http>
And somewhere in index.html file:
<a href="<c:url value="/logout" />" id="item-btn-logout">
<i class="icon-off"></i> Logout
</a>
The most important part is URL: /logout.
I have following code for spring security but it does not work. When I open log-in page and enter username/password which is admin#myproject.com / secret, following error message will be shown. Once username/password are entered following with be added to the address ?error=1, even if I remove it manually and refresh the page message does not go. Nothing is shown in console.
Your login attempt was not successful due to
Bad credentials.
spring-security.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<beans:import resource='login-service.xml' />
<http auto-config="true" access-denied-page="/notFound.jsp"
use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/member**" access="hasRole('ROLE_MEMBER')" />
<form-login login-page="/signin" default-target-url="/index"
authentication-failure-url="/signin?error=1" />
<logout logout-success-url="/login?logout" />
<csrf />
</http>
<authentication-manager>
<authentication-provider>
<user-service> <user name="admin#myproject.com" password="secret"
authorities="ROLE_ADMIN"/>
<user name="user#yahoo.com" password="secret" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
The form has following code, it seems like SPRING_SECURITY_LAST_EXCEPTIONis not empty even before submitting the form.
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<font color="red"> Your login attempt was not successful due
to <br />
<br /> <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />.
</font>
</c:if>
<form id="form-login" role="form" method="post"
action="<c:url value='/j_spring_security_check' />"
class="relative form form-default">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
I am not sure why, but the same code returns following error now
Your login attempt was not successful due to
Authentication method not supported: GET.
You need to allow everyone to access your /signin page, even if he is not authenticated.
<intercept-url pattern="/signin" access="permitAll" />
I wrote this answer before the question was changed the first time, at a time where the question was (it is still the title): "Spring-security shows 'Bad Credentials' even before submitting the form"
<intercept-url pattern="/member**" access="hasRole('ROLE_MEMBER')" />
<user name="user#yahoo.com" password="secret" authorities="ROLE_USER"/>
Above configs have two different Role names ROLE_MEMBER and ROLE_USER
UPDATE
Since Authentication method not supported: GET, can you try allowing GET.
<bean id="authenticationFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
p:postOnly="false" />
And the following change is also required in web.xml
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Hope this helps
The SPRING_SECURITY_LAST_EXCEPTION stays in the session even if you refresh the page. You need check for the error parameter:
<c:if test="${(not empty param.error) && (not empty SPRING_SECURITY_LAST_EXCEPTION)}">
I guess your login controller method is doing redirect or forward, and then tries to send a HTTP GET request to the login URL with the user name and password as query parameters. It is generally considered bad practice to send credentials as URL parameters and that's why is not allowed. It be should send a HTTP POST instead.
If you will want to stay with GET, you could bypass the check by using a request wrapper which returns HTTP POST instead of HTTP GET for getMethod.
Updated answer from #tharingu_DG should work, but it is still technically equivalent to sending unencrypted authentication credentials since anyone who steals it can use it to authenticate.
Newbie to Spring security. I had gone through some tutorials and implemented Spring Security. I have few pages which I secured via login.
Here is my spring-security.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/person*/*"
access="hasRole('ROLE_ADMIN')" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="password"
authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
From my index.jsp, when I try to access persons URL, it's asking for authentication. And I have logout URL. Inside persons JSP page.
<a href="<c:url value="logout" />" > Logout</a>
Controller
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return new ModelAndView("redirect:/");
}
It's working fine. Except few things. - When I try to go to /person/add, it's directly going to the page instead of asking the Authentication. Why? and how to resolve? Do I need to mention all URLs in intercept URLs (What if I have many?)
Well the main thing is, I'm trying to configure SSL as well for my application.
I installed this tutorial.
I have created ketstore
Configured in tomcat, server.xml
Configured in web.xml
Now I have the following in spring-security.xml
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/**"
requires-channel="https" />
<security:intercept-url pattern="/person*/*"
access="hasRole('ROLE_ADMIN')" />
</security:http>
The SSL is working. But Login is not working. When I go to persons URL, it's showing the page without asking for authentication. Why?
I tried adding access=hasRole('ROLE_USER'), then tomcat is showing Access denied when I give correct credentials.
How to solve it? I want to enable SSL for all URLs.
I'm using Spring 4.2.2.RELEASE and Spring Security 4.0.2.RELEASE
First, try to rewrite your security:intercept-url as following:
<security:intercept-url pattern="/person*" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/person/**" access="hasRole('ROLE_ADMIN')"
Regarding SSL, the tutorial is very nice and it should work out of the box, maybe the problem is again with intercepting url's, try my suggestion.
I'm trying to write my test spring security application with mkyong examples.
Spring Security: 4.0.0.RC1
Spring: 4.1.4.RELEASE
I have the following security config:
<http auto-config="true">
<intercept-url pattern="/admin**"
access="hasRole('ADMIN')"/>
<form-login authentication-failure-url="/?auth_error"
username-parameter="user"
password-parameter="password"
login-page="/"
default-target-url="/?OK"/>
<!-- <csrf/> -->
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="mkyong" password="123456" authorities="ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
login-page:
<html>
<body>
<form method="POST">
<label for="user">User: </label>
<input type="text" id="user" name="user" /> </br>
<label for="password">Password: </label>
<input type="text" name="password" id="password" /> </br>
<input type="submit" />
</form>
</body>
</html>
Now, when I try to login I get 403 error page:
Invalid CSRF Token 'null' was found on the request parameter
'_csrf' or header 'X-CSRF-TOKEN'.
description:
Access to the specified resource (Invalid CSRF Token 'null' was
found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.) has been
forbidden.
What's wrong, how can I fix that? I commented csrf in the config, but the error-message has to do with the csrf.
I had the same problem. I use thymeleaf and Spring boot, and got the CSRF token issue when I try to post data in a form.
Here is my working solution:
Add this hidden input:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
In your WebSecurityConfig (which extends WebSecurityConfigurerAdapter), add a method:
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setSessionAttributeName("_csrf");
return repository;
}
and add code in method configure():
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.csrfTokenRepository(csrfTokenRepository())
I spent lot of time on this problem. Hope it can help someone who has the same problem.
If you must disable it...
In Spring Security 4, CSRF is enabled by default when using the XML configuration. Previously it was only enabled by default for the Java-based configuration.
According to Section 14.4.2 of the Spring Security Documentation:
As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.
<http>
...
<csrf disabled="true"/>
...
</http>
Disabling CSRF protection sounds like a bad idea, no?
If you use Spring's Form Tag library the CSRF token will be automatically included. It will also HTML Escape form element values, which makes your site safer against XSS, and more correct.
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<form:form>
<form:input...
</form:form>
Otherwise, add this to your form:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
To #St.Antario,
Please use this code to enable CSRF in your code
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("*/*").authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
.and().csrf().csrfTokenRepository(csrfTokenRepository())
.and().addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
// Token is being added to the XSRF-TOKEN cookie.
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
//repository.setSessionAttributeName(("X-XSRF-TOKEN"));
return repository;
}
}
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<http pattern="/resources/**" security="none" />
<http use-expressions="true">
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
login-page="/login"
default-target-url="/home"
authentication-failure-url="/login?error=true" />
<logout
logout-success-url="/login"
delete-cookies="JSESSIONID" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="carlos" password="123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml, /WEB-INF/spring-security.xml</param-value>
</context-param>
add add jsp login
<%#page session="true"%>
and input hidden:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
What is your login page named
Is it ending with .jsp
If the login page is not ending with .jsp Spring framework doesn't evaluate the JSP or EL expressions
Soory for disgusting you. Actually i am poor in english. I am developing a spring application by using google app engige.
1. If the server is in running mode, for the first if i would try to log into the application. Firstly it should navigate to the
login page.
2. If any user wants to access aby page in the application by giving the page name like for example(in my application if i have ABC.jsp page, if the user wnat to access the file by giving 127.0.0.0:8888/ABC.jsp) it should navigate to the some default page which contains some message, and click here to navigate to the home page.
Now can you please tell how to do it in my application.
can you please tell me the step by step process to achieve this by using Spring MVC ,Objectify ORM and Google app engine.
Still don't quite understand what your problem is.
Add this to your web.xml:
<welcome-file-list>
<welcome-file>/login</welcome-file>
</welcome-file-list>
</web-app>
This ensures that if a user only types http://server:port she is redirected to http://server:port/login.
Now if you want that the user is also redirected to login if she types http://server:port/foobar.html, what you call "random page", which does not exist then you need an HTTP status code mapping.
<error-page>
<error-code>404</error-code>
<location>/login</location>
</error-page>
If you want that the user must always first authenticate (i.e. go through /login) first before any existing page is displayed you could use Spring Security for that. Example for simple basic-auth:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
<!-- HTTP basic authentication in Spring Security -->
<http>
<intercept-url pattern="/*" access="ROLE_USER" />
<http-basic />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="password" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
You can use spring security to do this. Have a look at
this link. The http tag should allow this. It will direct a user the login page for users that aren't authenticated. A sample context would be the following.
<beans:bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/jsp/login.jsp" />
</beans:bean>
<http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
<intercept-url pattern="/protected" access="hasRole('ROLE_protected')" />
<intercept-url pattern="/jsp/login.jsp*" filters="none"/>
<logout logout-success-url="/jsp/login.jsp" invalidate-session="true" />
<session-management invalid-session-url="/jsp/login.jsp?timeout=true" />
</http>