Can't link DB user with social networks with Oauth2 - java

I use SpringBoot Security and Spring Security Oauth2.
And i use OAuth2ClientAuthenticationProcessingFilter for login with social networks.
In this filter i use custom UserInfoTokenServices, with overrirded loadAuthentication(String accessToken)
In this method before return OAuth2Authentication i write social user id to DB user or create it, if does not exist (with extra logic i give him some password).
It works fine and later user can login with his email and password, as DB user or with his social network profile and it will be the same profile.
But now i need to link new social, when user already logged.
I tried to use same endpoint /socialName/login, but now super.loadAuthentication(accessToken) of UserInfoTokenServices throw:
Getting user info from: https://www.googleapis.com/oauth2/v2/userinfo
Could not fetch user details: class org.springframework.web.client.HttpClientErrorException, 401 Unauthorized
How to fix it? Or what should i do in this case?

Related

Spring boot LDAP auth in rest API without spring security

I have an API that is consumed by a mobile application that goes something like this:
#PostMapping("/myAPI")
public String getAgentProductsList(#RequestParam String username, #RequestParam String password, #RequestParam String productType) {
/*
here I need to verify the username and password in LDAP and retrieve the user's related data
*/
/*
some more code
*/
return "some products related to the user authenticated previously";
}
I need to do the authentication without using spring security or any redirection (that's what I've found in almost all the basic tutorial out there). So authenticating the username/password must happen inside the my endpoint.
That's my first time with LDAP so any helpful links or explinations is highly appreciated.

How do i make multiple logins for one account?

I make some website for myself(I want to add it to my CV) using Spring MVC, Security, and I have one question: I want to be able to login into my account using login OR email address, how do I accomplish this?
I have local database with users table that contains login,email and so on...
My Spring Security AuthenticationManagerBuilder configuration:
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("SELECT login,password,enabled from users where login = ?")
.authoritiesByUsernameQuery("SELECT login,role from users where login = ?");
So for example if I have users with login:Test and email:Test#gmail.com I want to be able to login using login Test, then logout and login via Test#gmail.com
Check for login or email, e.g.
where ? in (login, email)
Related question:
Logging in with either profile name or email in Spring Security

ldap & JWT authentication without spring security

I'm trying to create a security module that will check against LDAP for user credentials (on login) and on successful login generate a JWT for further requests to the server.
currently my module works like this:
i have 3 rest API endpoints to provide authentication (login, validate JWT, logout) that are not protected as anyone must be able to access those endpoints,
and also 1 userUpdate endpoint protected with spring security via a JWTAuthenticationProvider
all the stuff pertaining the JWT is ready, now I just need to create a method to check in LDAP if the user and password are correct. but i am having some trouble understanding how am i supposed to do so
i already have the master user and pass to conect to ldap, but most of the examples i find about ldap authentication are with spring security and i dont think thats the way to do it in this case as i need to verify the matching us/pass only on login (and not protect my endpoints with security).
can anyone tell me how im supposed to do that verification? any stuff i am not being clear on? please ask and comment and answer.
thanks
oh one edit:
#Override
public AuthenticationResponse login(AuthenticationRequest authenticationRequest) {
checkNotNull(authenticationRequest, "The authenticationRequest is a required argument!");
AuthenticationResponse authenticationResponse = AuthenticationResponse.builder().build();
//currently a pseudo authentication, here is where i should authenticate against LDAP
Optional<Usuario> optionalUsuario = service.findByNombreUsuario(authenticationRequest);
if (optionalUsuario.isPresent()) {
Usuario usuario = optionalUsuario.get();
String token = JwtTokenUtil.generateToken(authenticationRequest);
authenticationResponse.setAuthenticationToken(token);
repository.saveToken(UserToken.builder()
.nombreUsuario(usuario.getNombreUsuario())
.roles(usuario.getRoles())
.build(), token);
as you can see i intent to make the authentication against ldap only at login, and only to check if the user and pass are correct, i will manage the roles and authorities using other DB
another edit: i have some basic ldap structure for ldap auth using spring security, but i always get bad credentials
edit again: i managed to make it work with spring security, but (as expected) was told by my team that we need to implement that authentication without spring security to integrate with our custom role loader and token creation
use http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/ldap/authentication/LdapAuthenticationProvider.html to authenticate and get roles from LDAP, it should be done using spring security, I probably missed smth but could you explain why you don't want use it as far it is security standart

Understanding SignInAdapter in spring-social

Hello guys i read a lot about Spring-Social and i have a question. What is a parameter "userLocalId" in signIn method of SignInAdapter where it takes this id? I register user via facebook by fetching it information in register form. After this i want that he press signIn_button(facebook signIn) and have access to my site.
Should i do something like this: in SignInAdapter i getting connection to facebook and compare it's social information with fields in my users table?
The Spring Social Integration has 3 parts.
Signup
In Signup a local user is created based on the information provided by the provider
Connect
In connect we map a local user to the openID user
Signin
In signin we allows a openId authenticated user to log in to our application
Signin
In signin the SigninAdapter is used to load the local user so that the Spring Security layer can use it. Here the localUserId parameter will point to the Id of the user in our application. So in the adapter we need to load this user as an org.springframework.security.core.userdetails.User and set it to the SecurityContext.
ex:
LocalUser lu = getLocalUser(localUserId); // Load the local user from database
User user = new User(lu.username, lu.password, lu.authorities)
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(result);
Connect
Spring Social Providers a org.springframework.social.connect.web.ConnectController which will help us to link a local user to a openId user.
It requires you to send a POST request to /connect/<provider>, this will redirect the user to the login page of the provider where the user has to autherize the application.

How does Google App Engine User Service work internally?

I'm just curious about how Google app engine's user service works. The way I understand it, the user logged in state is stored in the cookie. To get the cookie, one has to have a http servlet request object (for java servlet at least). But the user service api doesn't require any http servlet request as input, so how does it get the cookie to check the whether the user is logged in or not?
Tim
During requests, user setup is handled by Google's servlet implementation.
[I]f the user is signed in and get the user's email address or OpenID identifier using the standard servlet API, with the request object's getUserPrincipal() method.
During the login process, the service works using redirects, similar to OpenID or OAuth. Take a look a the URLs throughout the login process.
Users are redirected to a URL, which is handled by App Engine, on your app, something like:
http://app.appspot.com/_ah/login?continue=http://app.appspot.com/dosomething
The login handler redirects to the Google login service, something like:
https://www.google.com/accounts/ServiceLogin?service=ah&continue=http://app.appspot.com/_ah/login%3Fcontinue%3Dhttp://app.appspot.com/dosomething&ltmpl=gm&ahname=Your+App+Name&sig=hf3322hdsk98fd8fh3u29hfh24as
You login, then Google redirects you back to the app engine login handler:
http://app.appspot.com/_ah/login?continue=http://app.appspot.com/dosomething
When Google redirects, some query parameters will be passed to the App Engine login handler, and the built-in login handler will set the cookie.
You are then redirected to the URL you specified, or where you 'started' from. Something like:
http://app.appspot.com/dosomething
What about the in the subsequent calls? For example (continuing from your point 4)
User calls the servlet http://app.appspot.com/dosomethingelse
In the servlet dosoemthingelse, I can again call UserService like this
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String userId = user.getUserId();
How does this userService instance gets the cookie to know who is the currently logged in user?

Categories

Resources