Setting up own security in Spring Boot - java

I have studied plenty tutorials and pages about Spring Boot Security. But none of them answered my questions. And here they are:
I´m building web app in Spring Boot. And I need to authenticate users via classic session (username, password). But as I know a lot of things are predefined in Spring Boot. And I want to change few things.
1) The only page which DO NOT NEED authentication is /. Here is also login form. Rest of pages MUST BE authenticated. So I do not want to use default URL /login. And what I have to write into form´s action?
2) I also need need unauthenticated routes for static resources. They are located: src/main/resource/static/css
3) Is there a way to edit logout? Like to add a code during logout action?
Can you show me how configure method of WebSecurityConfigurerAdapter should look like? I have already tried a lot of configurations, but they didnt work.
Thank you for your responses.

I recommend you to have a look at this tutorial for a specific login and logout page.
With antmatchers you can also define that your static content is not secured.See here
For adding logic between spring defined processes like logout you should have a look at the spring filter pipelines especially the Logoutfiler. This was already discussed here
It would also be an easy way to set the logout url to a rest endpoint, execute the action you want an then redirect to the auth service. In my opion the filter way is the better solution and cleaner.
I hope this helps to get on track. cheers

Related

Abnormal Behaviour of Web Browser

I was working on a Spring-security LDAP application. I'm following the link - https://spring.io/guides/gs/authenticating-ldap/ . Problem I'm facing is that I have made a very simple controller and a method to handle a request, returning a string. But browser is opening a login page (which I can't find anywhere). I deleted cache, restarted Eclipse and system both but to my dismay it displays the same page irrespective of any url configured in controller or any port. I'm unable to elucidate this behavior of browser.
If you had followed the guide exactly as it is, then you may notice that the file WebSecurityConfig.java has the following line http.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and().formLogin(); Which means that all your requests need to be authenticated. That means any end points that you define need to be authenticated too. They are secured by default.
You seem to have made a GET request to your endpoint, which is secured by Spring Security. If you want to create an unsecure endpoint then you have to make changes to the WebSecurityConfig file.
The login page that you mention is provided by Spring security library itself. It won't be available in your cloned project. At the end of the page they have also mentioned that the username is ben and password is benspassword. Spring security provides lot of default options which are useful. But, unless you read the documentation to understand what they are, you are in for quite a few surprises.

MySQL login Guidance? Spring boot security

Looking for some guidance on how to implement a login system. So I'm currently using this project: https://www.codebyamir.com/blog/user-account-registration-with-spring-boot for my registration, since it comes with a lot by default. Got everything working fine, so next step is a login system.
But my question is, what does "logging in" actually do to the MySQL db? I get the basic user+pass verification but I'm curious how it knows you are still logged in or how it persistently keeps you as the user you logged into? Wouldn't this be something with cookies?
Regardless, I thought I'd try to implement this example: https://medium.com/#gustavo.ponce.ch/spring-boot-spring-mvc-spring-security-mysql-a5d8545d837d
This confuses me. Following the code it looks like you do a GET request to /login to see the login page, then on login.html it does a POST request to the /login, but on the controller /login is only set to map get requests? Then somehow SecurityConfiguration.java does something to log you in?
TL;DR: I've been looking around for a while and can't make sense of this? Could someone please explain how logging in works or post some relevant tutorials how spring security works? Any advice is greatly appreciated!
The spring samples are always a good place to start.
https://spring.io/guides/gs/securing-web/
Although that doesn't include mysql.
You could try DZone they have good tutorials.
e.g. https://dzone.com/articles/spring-security-4-authenticate-and-authorize-users

How to use spring boot security for custom login page without configuration?

I am using spring security on spring boot app and I cannot use the custom login page I made. I want to use custom login page by default without using configuration controller, instead I want to change configuration from application.properties. Also I want to deny access to other pages until login successful. Please help me to log out of the application.
The Spring Security Reference provides an extensive guide on how to implement your custom login page.
I put together a small example in this repo
Spring Security With Customn login Page
An example of spring security with custom login page is provided along with that sitemash+hibernate is also implemented you have to create a database dumb is given in the readme file.

How can I replace my code in servlet filter with spring Interceptor?

I am new to the development of Web applications. For pre-processing of every request, I am using a servlet filter in which i get the requested uri and redirect it to a new uri if needed. Can i do the same with an interceptor class?
Also , what is the best way to redirect a user to the login screen if he is not logged in?
Thanks in advance
Can i do the same with an interceptor class
: Yes you can do the same, here is a simple tutorial to get you started with interceptors: https://dzone.com/tutorials/java/spring/spring-interceptor.html
what is the best way to redirect a user to the login screen if he is
not logged in?
If you are already using Spring then use Spring security it comes with a lot of features.

Using JaaS with Jersey on Grizzly

I'm trying to find a simple, flexible way to add JaaS authentication to REST. I found a post that I think leads me in the right direction (See StevenC's answer). It sounds like the servlet container is responsible for security, not the Jersey code itself. I like this idea, but need a little guidance on implementation.
Grizzly is my servlet container and I want to configure it to use JaaS for authentication. For now, a simple username/password combination would be fine, and hard-coding the username/password pairs directly in code is fine. As long as it uses JaaS, we can refine those details later.
As far as what is sent over HTTP, I'm thinking that storing a cookie would be the easiest way to make this all work. Whatever it takes to keep authentication junk away from my Jersey code.
Here's the code to start Grizzly so far:
final String baseUri = "http://localhost:9998/";
final Map initParams = new HashMap();
initParams.put("com.sun.jersey.config.property.packages",
"my.jersey.Service");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
If this whole process works, what's the best way to check permissions for the user? I would probably want my REST code to actually validate permissions at certain points. Am I even on the right track? Is there an easier way? A link to a tutorial would be a great answer. Even an answer like "I did that and it worked" would give me a warm fuzzy that I'm heading in the right direction.
Thanks for any help.
EDIT: Some clarifications for StevenC's comment:
Do you still want to use servlet filters to protect your resources? I'll use whatever can separate out the authentication detail from the Jersey code. It doesn't have to be servlet filters.
What is mean by "configure it to use JaaS"? The original plan was to protect the current API using JaaS. The next phase would be to make the entire API available online. It seemed to make sense to have a Jersey wrapper around the API calls, but keep authentication handled by Grizzly. Grizzly would have to interact with JaaS at that point I believe.
Are you thinking there should be some config that simply causes grizzly to protect your resources? I was considering a two-step process of authenticating the user and based on roles, authorizing the user to access resources. The idea was to have Grizzly handle authentication (using JaaS) and Jersey handle authorization.
"I don't see the need for the usage of cookies with a RESTful resource." It would be wonderful to remove the use of cookies, but how can the be accomplished? The system needs to know if the user is authenticated. I'd rather not ask them to pass a username/password/etc for each call. Even passing a session token as a parameter with every call seems "ugly".
Also, please note that I'm fairly new to REST. I've been doing SOAP for a couple of years, so I may have a "SOAP bias" that may be blinding me from some obvious, simple solution that everyone uses. If there's an easier way, please feel free to share. I'm just trying to learn as much as possible.
I'm not entirely clear what is meant by "configure it to use JaaS for authentication". If there's a simple configuration to have grizzly enforce HTTP authentication protecting URLs, I don't know about it.
I'm assuming from the other question and answer you reference that you want to use a servlet filter. Normally that's configured in the web.xml file of a servlet project. Grizzly is of course often used to start up a server from code as opposed to application config. When I used grizzly in this way I noticed that GrizzlyWebContainerFactory didn't offer any versions of create() that allowed you to specify servlet filters. However I did notice ServletAdapter [1] in the same project that does give you that ability.
As for the filter itself, I unfortunately don't know of a pre-built servlet filter that simply plugs JaaS configured login modules into your application, so you'll likely have to write a bit of code there. It's not much though, just choose the HTTP based authentication method (e.g. HTTP BASIC, DIGEST, etc.), extract credentials from the request accordingly, and login using the JaaS framework. I don't see that a cookie would specifically be needed for RESTful resources. The RESTful architectural style frowns upon keeping sessions. There are plenty of tutorials about JaaS otherwise, so I won't elaborate on that here.
Once a JaaS subject is active (consumer successfully logged in) you can simply get the current subject and check the active principals and credentials using the Subject.getSubject method.
Anyway, this answer is specifically to give a bit more of the details around doing auth with servlet filters, as you requested in the other (linked) question. This isn't necessarily the only way to do auth in a jersey webapp, but it's a fairly straightforward way to do it. I like it because it keeps me from injecting repetitive auth code in each resource that needs it.
[1] https://grizzly.dev.java.net/nonav/apidocs/com/sun/grizzly/http/servlet/ServletAdapter.html
Not sure if you are asking how to secure each resource, but I found a presentation on javapassion that sounds like what you are looking for. He says to use #Context SecurityContext as a parameter.
#Path("basket")
// Sub-resource locator could return a different resource if a user
// is a preferred customer:
public ShoppingBasketResource get(#Context SecurityContext sc) {
if (sc.isUserInRole("PreferredCustomer") {
return new PreferredCustomerShoppingBaskestResource();
} else {
return new ShoppingBasketResource();
}
}

Categories