Defining roles post Google SSO in Spring Boot - spring

I have implemented Google SSO in my Spring Boot application and now need to make certain people admins while everybody else is a user. In the returned google user object, it doesn't explicitly send the username (just the email) but I have tried passing both as arguments to withUser() and it doesn't seem to work.
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
auth.inMemoryAuthentication()
.withUser(<username>).authorities("ROLE_ADMIN");
}
Anyone know if there's another way to do this? Thanks a bunch!
PS: I'm basically following this guide right here: http://www.techforumist.com/google-oauth2-login-in-spring-boot-and-angularjs so you can see what the code looks like.

Related

Edit Static User in Spring Security

I have a java app written by a developer. The app is using Spring Security and uses static usernames and passwords. I'm trying to find where the usernames are stored so that I can add new users and remove old ones.
I'm using Eclipse IDE to view the source code. Any help is much appreciated.
Thanks
Search after a class that extends WebSecurityConfigurerAdapter (so basically search after this string in code). Look over the file you have found. Either there are your credentials directly, or post the content you find there.
In spring-security chances of having static user credentials are:
In application property file
spring.security.user.name=
spring.security.user.password=
In configure method of WebSecurityConfigurerAdapter extended class:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("USERNAME")
.password("USERPASSWORD");
}
this are two ways of creating static users.

How to Apply no filter on the specific end point

I am using spring boot and spring security for web applications. I wanted to apply for no filter on my public API. Now what I am doing is the equality check on the path which is sent by the client and the path which I have hard code if it is equal then I am not applying the filter.
Code sample
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return request.getRequestURI().equals("api/v1/public/hello"));
}
But this approach is not a good way to do. As in, there can be multiple public endpoints and I can't put an equal check on each of them. I need a solution where I can have all my public endpoints in one place and when the request comes I simply have to check in that one place if it is present then no filter will be applied.
Assuming you are talking about the Spring Security Filters and you may want to expose some APIs publicly.
You may use configure(WebSecurity web) or configure(HttpSecurity http) method to achieve the goal. To prevent the filters to be applied you may use configure(WebSecurity web) method. This will omit the request pattern from the security filter chain entirely. Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible.
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("api/v1/public/**");
}
use antMatcher to exclude your public domain.
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers("api/v1/public/**", "/health").permitAll()
.anyRequest()..authenticated();
Usually, closing your app for all and opening for the desired endpoint is the best security practice.

Unable to Authenticate a User with an LDAP Server using LDAP User Search Query with Spring Security

LDAP Server Hierarchy as retrieved via Apache Directory Studio:
Root DSE:
DC=company,DC=com
OU=Offices
OU=Region Offices
OU=Region1 Office
OU=Users
CN=Jayesh Mulwani
WebSecurity is enabled as a part of below class:
public class LDAPSecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.ldapAuthentication()
.contextSource().url("ldap://server-url/CN=auth_support,OU=Misc,DC=company,DC=com")
.managerDn("username").managerPassword("password")
.and()
.userSearchBase("OU=Offices,DC=company,DC=com")
.userSearchFilter("(&(objectClass=user)(cn={0}))");
}
}
Once the application is setup on tomcat, i enter the username along with its password but the authentication fails and no error is prompted.
Can someone please assist me with the approach or specify if i'm missing something here ?
I have fixed the problem by adding the below two conditions
.groupSearchFilter("(&(objectClass=group)(AccountName={0}))")
.groupSearchBase("CN=DEPT_All_Employees,OU=DepartmentSecurityGroups,OU=Resources,DC=company,DC=com")
I referred this example to fix the issue http://www.jcombat.com/spring/spring-security-ldap-authentication

Issue with the spring security tutorial on spring.io

I am trying to run the spring security application on the official website. When I try to access the context root I get the user authentication prompt even though .antMatchers("/", "/home").permitAll() allows all access to /home and /. Also the password is being set in the application in the following code
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
However I still get the Using default security password message in the logs with the password mentioned. Please could you help.
Edit:
I had made a mistake in the code, I forgot to annotate the WebSecurityConfig class with #Configuration and #EnableWebSecurity annotations.
The password which you find from log is from basic auth which is by default enabled, you can do httpBasic().disabled() to disable it, then you will not see the default password any more.
Update
I saw you are using spring-boot, which makes live much easier, try add this property: security.basic.enabled=false, it should help you to disable it..

Spring Boot: Secured RESTful API using Spring Social and Spring Security

I am trying to define and secure a RESTful API using Spring Boot. Ideally, I would like to use Spring Social and allow clients (web and mobile) to login via Facebook.
What is working
So far, I managed to have a working API using #RestController and secure it with a basic Spring Security configuration as follows:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/**").authenticated()
.antMatchers(HttpMethod.PUT, "/api/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
.anyRequest().permitAll()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
The antMatchers could probably be improved, but I made it like this for my own clarity for now and it works fine. Doing GET requests is allowed and all others required to send the standard user:password given by Spring Security at runtime. An example using httpie:
http POST user:a70fd629-1e29-475d-aa47-6861feb6900f#localhost:8080/api/ideas/ title="My first idea"
Which right credentials, it sends a 200 OK back, otherwise a 401 Unauthorized.
Spring Social
Now, I am stuck and can't get my head around using Spring-Social-Facebook to get working with my current setup and keep fully RESTful controllers. Using standard forms and redirects seems trivial, but I couldn't find any solution for a REST-based approach that easily supports web and mobile clients for example.
As I understand, the client will have to handle the flow, since the back-end won't send any redirects to the /connect/facebook URL.
I followed the tutorial Accessing Facebook Data and it works on its own. However, I would like to avoid having to have those facebookConnect.html and facebookConnected.html templates like in the tutorial. So I don't know how to have change that.
Another Spring Boot tutorial for OAuth is also nice and working, but I would like to stick with Spring Social if possible due to the simplicity.
This post, helped for the Method not allowed issue of the /connect/facebook redirect when using those views mentioned above.
Post about Social Config. Probably, I am missing something there.
Any advice, solution or link to a better tutorial would be really helpful.
Thanks!
UPDATE 1
Now, I have a working website with traditional User SignUp and Login over forms. I have a "Login with Facebook" button that sends me over the "OAuth dance". So next issue is that I have to create somehow the User manually after the Facebook login has been successful, because for the moment both "logins" are not related, so even though the user is logged in with Facebook, he doesn't yet have an associated User object with the right authorisations.
SocialAuthenticationFilter by default, redirects to '/signup' in the case you described, user is signed in from a social app, however, no local account exists. You can provide a handler to create a local account. This is also covered in the spring-socal samples.
#RequestMapping(value = { "/signup" }, method = RequestMethod.GET)
public String newRegistrationSocial(WebRequest request, Model model) throws Exception {
String view = "redirect:/home";
try {
Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);
if (connection != null) {
UserProfile up = connection.fetchUserProfile();
registerUser(up.getFirstName(), up.getLastName(), up.getEmail(), "DummyPassword");
providerSignInUtils.doPostSignUp(up.getEmail(), request);
//SignInUtils.signin(up.getEmail());
...
...
}
}
return view;
}

Resources