Spring security don't asks for login and password [duplicate] - spring

My application can have below URLs:
/siteadmin/homepage/
/siteusers/customer/createCustomer
Below is my spring-security.xml:
<beans:beans>
<http auto-config="true">
<intercept-url pattern="/siteusers***" access="isAuthenticated()" />
<!-- <intercept-url pattern="siteusers/home/*" access="hasRole('USER') OR hasRole('ADMIN')" /> -->
<intercept-url pattern="/siteadmin***" access="hasRole('ROLE_ADMIN')" />`enter code here`
<form-login login-page="/siteusers/loginprocess/login" default-target-url="/siteusers/home/homepage"
login-processing-url="/siteusers/loginprocess/login"
authentication-failure-url="/siteusers/loginprocess/login?error" username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/siteusers/loginprocess/login?logout" logout-url="/siteusers/loginprocess/logout" />
<!-- enable csrf protection -->
<csrf />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="b" password="123456" authorities="ROLE_ADMIN" />
<user name="a" password="a" authorities="ROLE_USER" /><!-- This user can not access /admin url -->
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
If I logged in with user 'a' and hit URL http://localhost:8080/siteadmin/homepage/ it is allowing user 'a' to view the page although his role is not admin. But when I try to hit http://localhost:8080/siteadmin then Spring Security is working fine ie. its showing access denied page.
I want to restrict /admin/* URLs for users who doesn't have Admin role.

See AntPathMatcher:
The mapping matches URLs using the following rules:
? matches one character
* matches zero or more characters
** matches zero or more directories in a path
Some examples:
com/t?st.jsp - matches com/test.jsp but also com/tast.jsp or com/txst.jsp
com/*.jsp - matches all .jsp files in the com directory
com/**/test.jsp - matches all test.jsp files underneath the com path
org/springframework/**/*.jsp - matches all .jsp files underneath the org/springframework path
org/**/servlet/bla.jsp - matches org/springframework/servlet/bla.jsp but also org/springframework/testing/servlet/bla.jsp and org/servlet/bla.jsp
Your pattern /siteadmin***misses slashes. Use /siteadmin/**.

Related

How to handle simultaneous logins?

In my webapp the login page is http://localhost:8080/vsingh/login
I am able to do below
Open tab1 and open the login page
Open tab2 and open the login page
In tab1 login with USER1. User is redirected to homepage. Now open tab2 and login with USER2. Now user is redirected to homepage of USER1.
How can I logout USER1 automatically in this case? Any pointers are appreciated.
PS: I do redirect automatically to homepage is user is already logged in and hits the login page, however in this case, the tab was already open before the user attempted login
#RequestMapping("/login")
public String login() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken) && auth != null) {
return "redirect:userHome";
}
return "login";
}
Spring Security XML
<http auto-config='true' use-expressions="true">
<intercept-url pattern="/*" access="permitAll" />
<access-denied-handler error-page="/login"/>
<form-login login-page="/login"
authentication-failure-handler-ref="customAuthFailureHandler"
username-parameter="username" password-parameter="password"
authentication-success-forward-url="/userHomeX" />
<csrf />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<password-encoder ref="encoder" />
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT USERNAME, RTRIM(PASSWORD) AS PASSWORD, CASE WHEN ENABLED=1 AND ADMIN_LOCK = 0 THEN 1 ELSE 0 END AS ENABLED FROM JWBDATABASE.JWBSCHEMA.USERS WHERE USERNAME=?"
authorities-by-username-query="SELECT USERNAME,USER_ROLE AS ROLE FROM JWBDATABASE.JWBSCHEMA.USERS WHERE USERNAME=?" />
</authentication-provider>
</authentication-manager>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
<beans:bean id="customAuthFailureHandler"
class="com.vj.authenticationManager.CustomAuthFailureHandler">
</beans:bean>
Why it is not duplicate?
Question is not about allowing multiple logins in different tabs but somehow force a single login for all tabs. If someone logins thru an already open login page with a different userid, either the old one should be forced logged out or throw an error on new login with some message

Failed to evaluate expression with spring security

I have a Spring rest service, and I'm trying to add security to it. I followed this tutorial, but when I try to access the service directly I get the following error:
There was an unexpected error (type=Internal Server Error,
status=500). Failed to evaluate expression 'ROLE_USER'
Here's my security configuration:
webSecurityConfig.xml
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login
authentication-success-handler-ref="mySuccessHandler"
authentication-failure-handler-ref="myFailureHandler"
/>
<logout />
</http>
<beans:bean id="mySuccessHandler"
class="com.eficid.cloud.security.rest.AuthenticationSuccessHandler"/>
<beans:bean id="myFailureHandler" class=
"org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="temp" password="temp" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
SpringSecurityConfig:
public class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
}
I'm also getting this error when trying to use curl to log in:
{
"timestamp":1460399841286,
"status":403,"error":"Forbidden",
"message":"Could not verify the provided CSRF token because your session was not found.",
"path":"/spring-security-rest/login"
}
Do I need to add the csrf token manually to the command? The service has a self-signed certificate, if that makes any difference.
If you don't need CRF to be enabled, then you can disable it in webSecurityConfig.xml file like below:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.html" access="hasRole('ANONYMOUS')" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- This form is a default form that used to login
<http-basic/>
-->
<form-login login-page="/login.html"/>
<csrf disabled="true"/>
</http>
If CSRF is enabled, you have to include a _csrf.token in the page you want to login or logout.The below code needs to be added to the form:
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
You need hasRole('ROLE_USER') in the intercept-url element.
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
See the docs for the other expressions, that you can use.
Spring security blocks POST requests.
To enable it you can either:
Add after all you forms requests :
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" class="form-control" />
(For example:
<form id="computerForm" action="addComputer" method="POST">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" class="form-control" />
)
Or if you use anotation, you can allow POST directly in your code by adding the csrf().disable on your WebSecurityConfigurerAdapter (I havent found the xml equivalent yet) :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and().formLogin()
.csrf().disable()
;}

spring security and angularjs redirecting back to given url after login

I have a web application using spring 3.2.The login process is done through spring security.When a user gives a url to view the profile of a particular user he will redirect to login page if he is not logged in.I need to go back to the user's profile if he is not successfully logged in.Since I am using angular js my urls are in the form
http://mydomain.com/#/view-profile/71 to view the profile of the user.If I am not logged in it will redirect to login page.In the browser url becomes http://mydomain.com/login#/view-profile/71 but after successful login it is not redirecting to the specified url.How can I make that with angularjs.
In app.js I have given like this
$routeProvider.when('/view-profile/:id',
{
templateUrl: '/partials/editor/view-profile.htm',
action: 'kc.view-profile',
resolve: {
loadData: ViewCtrl.loadUserProfile
}
}
);
And for authentication in security.xml it is written like
<http use-expressions="true">
<!-- Authentication policy -->
<form-login login-page="/login" login-processing-url="/j_security_check" authentication-failure-url="/login?error=true"/>
<logout logout-url="/signout" delete-cookies="JSESSIONID" />
<intercept-url pattern="/assets/**" access="permitAll" />
<intercept-url pattern="/application/signin/**" access="permitAll" />
<intercept-url pattern="/application/signup/**" access="permitAll" />
<intercept-url pattern="/application/manage/**" access="ROLE_EDITOR" />
<interce
pt-url pattern="/application/**" access="isAuthenticated()" />
<!--<intercept-url pattern="/application/connect/**" access="permitAll" />-->
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDao">
<password-encoder ref="passwordEncoder"/>
</authentication-provider>
</authentication-manager>
Spring Security doesn't support Ajax login out-of-the-box, that's why your application isn't working correctly.
You can have a look at this sample application that handles Ajax login/logout with AngularJS + Spring Security:
https://github.com/jhipster/jhipster-sample-app
I had to implement some specific Ajax handlers, as you can see here:
https://github.com/jhipster/jhipster-sample-app/tree/master/src/main/java/com/mycompany/myapp/security

Spring security 3.2.0 > <security:form-login /> deprecated

I have a problem with spring security 3.2.0 RC1
I'm using the tags to connect me
<security:http>
<security:intercept-url pattern="/paginas/**" access="ROLE_ADMIN"/>
<security:form-login login-page="/publico/login.xhtml" always-use-default-target="true"
default-target-url="/paginas/funcionario.xhtml" authentication-failure-url="/publico/login.xhtml?login_error=1"/>
<security:logout invalidate-session="true" logout-success-url="/publico/login.xhtml"/>
<security:remember-me/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSourceMySQL"
users-by-username-query="select usuario, senha, ativo from funcionario where usuario = ?"
authorities-by-username-query="select f.usuario, f.permissao from funcionario f where f.usuario = ?"/>
</security:authentication-provider>
</security:authentication-manager>
<security:form-login />
This says "Method 'setFilterProcessesUrl' is marked deprecated"
<security:logout />
This says "Method 'setFilterProcessesUrl' is marked deprecated"
Could someone tell me any alternative?
Thanks!
I'm not sure if this answer can help you.
However, the warning message generated by IDE is not a big problem because you did not use the deprecated method.
I'm using spring security too and I also can see the same warning message but the service is working perfectly.
I'm sorry if the answer is not you wanted.

SSL only during login with spring security

I'm trying to use https only during login.
The problem is that when the application tries to switch from https to http I end up being redirected to the login form (as if the session is getting destroyed).
Here is the configuration I'm using:
<s:http auto-config="true" access-denied-page="/erro-403"
create-session="never">
<s:port-mappings>
<s:port-mapping http="8080" https="8443" />
</s:port-mappings>
<s:intercept-url pattern="/preferencias" access="IS_AUTHENTICATED_REMEMBERED"
requires-channel="http" />
<s:intercept-url pattern="/admin/**" access="ROLE_SIPAS_ADMIN"
requires-channel="http" />
<s:intercept-url pattern="/area-prestador/**"
access="ROLE_SIPAS_PRESTADOR, ROLE_SIPAS_ATENDENTE, ROLE_SIPAS_ADMIN"
requires-channel="http" />
<s:intercept-url pattern="/**"
access="IS_AUTHENTICATED_ANONYMOUSLY,IS_AUTHENTICATED_REMEMBERED"
requires-channel="https" />
<s:form-login login-page="/login" default-target-url="/"
authentication-failure-url="/login-error" always-use-default-target="false" />
<s:logout logout-url="/logout" logout-success-url="/" />
<s:remember-me />
</s:http>
<s:authentication-manager>
<s:authentication-provider user-service-ref="authenticationMBean">
<s:password-encoder hash="md5" base64="true" />
</s:authentication-provider>
</s:authentication-manager>
The only workaround that I've found is to check the remember-me option.
Any ideas of what am I doing wrong?
Although it's been a long time this question was posted and I am sure the author must have found a solution already, I am posting this answer for future reference.
This issue is discussed in Spring Security FAQs. A quick solution is to add this element to your s:http element:
<s:session-management session-fixation-protection="none"/>

Resources