Spring Security restricting access to certain roles at certain url levels [duplicate] - spring

This question already has answers here:
How to fix role in Spring Security?
(2 answers)
Closed 2 years ago.
I'm trying to understand Spring Security and I have a page that asks you to login at startup and then the user has a role. I'm trying to say that all roles can access the welcome page, but if you want to login to the admin page then you can only be either an EMPLOYEE or a USER.
Here is the configure method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/*").hasAnyRole("EMPLOYEE", "USER","NONE1")
.antMatchers("/courierapp/admin").hasAnyRole("EMPLOYEE","USER")
.anyRequest().authenticated()
.and().formLogin();
}
Why is it that /courierapp/admin is still able to be accessed if I have a role of "NONE1" for example?

If anyone else is having an issue with Spring Security using antMatchers, it is first one matches so in this case I had to do:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasAnyRole("EMPLOYEE","USER")
.antMatchers("/").hasAnyRole("EMPLOYEE", "USER","NONE1")
.anyRequest().authenticated()
.and().formLogin();
}
This makes it so only employees and users will be able to access /admin. Also, if there is a base path in your url and you don't know where it's coming from, that's just the root path.

Related

Spring security user manual login session creation without password by admin

I am building a web application with spring, hibernated for backend and I am using html,css, javascript jquery forfrontend . I have created signup page, login page and home page. The flow is, User creates account and logins with username and password and if he is authenticated then he is redirected to home page. We do not store password in plaintext form for security reasons. Now I am the administrator and creator of the web application and sometimes a need arises for admin to change data for user or demonstrate what user can do in the interface. What I need to do is create a login session of the user and make changes in his account and/or demonstrate how user can do things on the website(by sharing screen). I want to create a user's session manually, as password is stored in plaintext form I can not login with username and password. Is there a way I can create browser login session without password. I am sharing screenshots of my web applications login page and home page. I am also sharing spring security configuration class. Is there a way I can just specify a username and spring can create a login session for me and I can access user's account just like a normal user session.
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// add a reference to our security data source
#Autowired
private DataSource myDataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(myDataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/signup_page","/forgot_password","/signup","/reset_password").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login_page")
.loginProcessingUrl("/authenticateTheUser").permitAll()
.defaultSuccessUrl("/home_page")
.and()
.logout()
.logoutSuccessUrl("/login_page?logout")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.permitAll()
.and()
.sessionManagement()
.sessionFixation()
.migrateSession()
.invalidSessionUrl("/login_page")
.maximumSessions(3)
.expiredUrl("/login_page?logout");
}
}
below are the images of my web application.
Two concepts that you may want to look into are:
Pre-Authentication, normally for cases where you are behind a gateway that performs authentication prior to your application (see RequestHeaderAuthenticationFilter)
Switch User for cases where an ADMIN needs to impersonate a USER (see SwitchUserFilter)
Both of these require careful consideration and proper use so as not to accidentally open you up to bypassing authentication entirely. If you're just doing this in a development environment, enabling pre-authentication by adding a RequestHeaderAuthenticationFilter could work for you.

Spring security 5 - UsernamePasswordAuthenticationFilter and basic authentication

I'm trying to implement simple security for a small API school project and am a bit confused and overwhelmed. I followed
this blog post.
Everything works and I'm able to login and receive a jwt token. However login is currently performed by sending the username and password along with the URL as query parameters. That is of course something I would like to avoid.
I have tried adding httpbasic to the security configuration like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtAudience, jwtIssuer, jwtSecret, jwtType))
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/board/**").hasAnyRole("MEMBER", "BOARD")
.antMatchers("/members/**").hasRole("MEMBER")
.anyRequest().authenticated()
)
.httpbasic().and().
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
Login however ceases to work and I constantly get an unauthorized while trying basicAuth with postman.
So my question is: How can I change the behaviour of these code snippets to accept basic authentication and not send user credentials by URL? Do I have to override the AttemptAuthentication method too?

how to use .antMatchers("/").not() method in spring security, and i am using spring MVC

I wanted to permit 100 url's if the user do not have the given permission and also want to restrict him only to a single page, how can i do it using spring security, or can someone help me with antMatchers() to proceed with my requirement, thank you in advance.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() .antMatchers("/p1/**").permitAll()
.antMatchers("/p2","/p3","/p4").wantRestrictIfItHasRole.access("hasRole('ROLEA')")
.anyRequest().authenticated();
}

How can I allow public access to parts of Spring Security app using permitAll?

I'm trying to get a Spring application to allow some requests to public (without login) and some requests to private (with login).
At this point I'd like to just get the public part to work properly.
I have tried most of the example configurations listed on the Spring Security documentation, including all sorts of combinations of anonymous(), and permitAll(). All end up redirecting to the login page.
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about","/api/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}
Expected result: items under permitAll() are accessible without logging in
Actual result:
redirect to login page. This shows up in the log: 2019-06-06
17:29:43.593 INFO 56330 --- [ main]
o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any
request, [org.sprin...
This leads me to believe that it isn't even reading this configuration. Is there any way to fix this?
Thanks!
UPDATE: I tried adding the websecurity ignores, and it doesn't appear to be working still. It appears to still print the "defaultsecuritychain" error so I feel like this may have something to do with it.
UPDATE 2: Added application.properties file under src/main/resources with this line logging.level.org.springframework.security=DEBUG to make it log debug messages.
pastebin.com/2u9k7eHD
Have a look at http://blog.florian-hopf.de/2017/08/spring-security.html, it may explain your use-case in more detail.
My recommendation is to try and use WebSecurity for static and public resources
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/signup", "/about","/api/home");
}
You can achieve your requirements with below configurations. It's a good way to use the URLs which does't require Authentication/Authorization to be placed in WebSecurity using ignoring instead of HttpSecurity as WebScurity will bypass the Spring Security Filter Chain and reduce the execution time
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/signup", "/about","/api/home");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.yourConfigurations
}
When you use HttpSecurity and try to permitAll() requests. Your requests will be allowed to be accessed from the Spring Security Filter Chain. This is costly as there will be requests other requests which would also come into this filter chain which needs to be allowed or disallowed based on Authentication/Authorization
But when you use WebSecurity, any requests to "/resources/**", "/signup", "/about","/api/home" will completely by pass the Spring Security Filter Chain all together. It is safe because you don't need any Authentication/Authorization to be in place to see an image or read a javascript file.
Turns out that I was missing the #SpringBootApplication annotation all along in one of my source files. Make sure that's in there and perhaps it will work.
Thank you to all who replied!

how to implement a authentication with spring boot security?

i am using spring boot. i want to post a username and password params to login, and if login success then return a token. after, i will use the token to judge login status. here is my security configure code. but i don't konw where to write the login authentication logic code.
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and()
.formLogin()
.loginPage("/user/unlogin")
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/login")
.antMatchers("/user/logout")
.antMatchers("/user/register");
}
}
==========================
thank you !
There's always more than one way to do something with Spring. There is a happy path (probably) with Spring Boot, and you seem to have started on it. Note though, if you want Boot to provide some default behaviour, then don't use #EnableWebSecurity (as advised in the user guide). The web-secure sample has an example you can follow.
If you use formLogin() the default login URL is /login (not /user/login), so you should be able to post the username and password to that endpoint to authenticate. Don't add /login to the unsecured paths using web.ignoring() or Spring Security will never process it. When you post to /login you get back a JSESSIONID cookie. That's your authentication token, and it expires when the session expires in the server (30min by default, but easily configurable). Include it in future requests for secure resources - some HTTP clients will even do that for you (like a browser does).

Resources