Getting Basic Authentication Headers Springboot - spring

I am using Spring boot for my application with Basic Authentication for the rest api.
I would like to get the username and password of the request being authenticated to do some more fine grained authorization tasks. How can I process the HttpHeaders to get the details?

You can use the #AuthenticationPrincipal annotation, to get the logged in user as a parameter for your controller function.
#RequestMapping(method = RequestMethod.GET, consumes="application/json")
public ResponseEntity<> searchMeta(#AuthenticationPrincipal UserModel activeUser) {
//Do your processing with the UserModel
}

Related

Spring Boot Security , Form based login to invoke a custom API for authentication

So wondering if it's possible or not. I'm trying to authenticate my rest API's in spring boot with a post API which is already present which validate the user.
I'm using fromLogin based authentication and trying to invoke that Rest Controller and use that login API by passing the post parameter. There I'm creating the spring security context
I'm trying to invoke the POST API of login on login submit. Authentication is not working.
Can we achieve this using form login? Let me know if my understanding very new to spring boot security
My code somewhat looks like this
Controller
#RestController
#RequestMapping("/somemapping")
public class AuthController {
#RequestMapping(value = "/login", method = RequestMethod.POST)
public UserData authenticateUser(#RequestBody(required = true) UserInfo userInfo, HttpServletRequest request) {
// get user data goes here
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userdata.getUsername(), userdata.getPassword(), new ArrayList < > ());
authentication.setDetails(userdata);
SecurityContextHolder.getContext().setAuthentication(authentication);
send the info to caller
return userdata;
}
//Security Adapter
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/somemapping/**", "/login*", ).permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/")
.and().authenticationEntryPoint(authenticationPoint);
}

Is it good idea to take user id from SecurityContextholder in spring boot RestController..?

I am developing spring boot rest application for an ecommerce app, suppose i have endpoint /shipping-address which will fetch all the saved addresses for the user, is it good idea to take user id from SecurityContextHolder like
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Long userId;
if (principal instanceof UserPrincipal) {
userId = ((UserPrincipal) principal).getId();
}
or should i pass from the client side in the request body..? which is correct..? If i take from SecurityContextHolder is it problem when it comes to Horizontal scaling..??
Please help, i am new to backend development. Thanks.
Taking the userId from the SecurityContext is a good idea because it will prevent from hacking your application.
If you pass the userId from the client somebody could intercept the request and change the userId.
In regards to scaling it depends how you authenticate the user. If it's basic or token based and does not rely on session information. Everything will be fine.
SecurityContext
There is no problem in using a SecurityContext with Spring MVC.
You could use something like :
#RestController
#RequestMapping(path = "/auth")
#Slf4j
public class AuthResource {
#GetMapping(path = "whoami", produces = MediaType.APPLICATION_JSON_VALUE)
#PreAuthorize("isAuthenticated()")
public ResponseEntity<String> whoami(#AuthenticationPrincipal() UserDetails userDetails) {
String login = userDetails.getUsername();
return ResponseEntity.ok(login);
}
}
The annotation #AuthenticationPrincipal from Spring Security will simplify your code.
Session storage
By default, the session will be backed by the HttpSession (cookie JSESSIONID).
So you'll need something like sticky sessions if using a load balancer.
However, sessions can be stored elsewhere, like in relational databases (JDBC) or in Redis : this is what Spring Session can do.
See also Control the Session with Spring Security.
You can also choose to not use sessions with Spring Security :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Spring security: what function does AuthenticationManager.authenticate() perform

I have been studying Spring security with JWT for a while and i noticed that at every tutorial I read, the username and password is taken, wrapped in a UsernamePasswordAuthenticationToken and passed on to a AuthenticationManager.authenticate() somthinglike this :
#RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(#RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
// Reload password post-security so we can generate the token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
my question is what does the authenticate method do, why is it used ?
From the Spring Security Reference:
AuthenticationManager is just an interface, so the implementation can be anything we choose. (...) The default implementation in Spring Security is called ProviderManager and rather than handling the authentication request itself, it delegates to a list of configured AuthenticationProviders, each of which is queried in turn to see if it can perform the authentication. Each provider will either throw an exception or return a fully populated Authentication object.

How to have Spring Security enabled for an application using third party login?

I have a Spring Boot enabled application whose login is controlled by third party Siteminder application. After successful authentication, Sitemeinder redirects to our application url. We fetch the HttpRequest from Siteminder and process the requests.
Now, how can Spring security be enabled in this case for authorizing users based on roles.
#Controller
public class LoginController
#RequestMapping( value= "/")
public void requestProcessor(HttpServletRequest request)
{
.
.
.}
The above controller's request mapper reads the request coming from SiteMinder and processes the request which has the Role of the user logged in. Where can we have Spring Security enabled to authorize pages and service methods to the user.
This is an scenario for the PreAuthenticated security classes:
Take a look here:
http://docs.spring.io/spring-security/site/docs/current/reference/html/preauth.html
Spring Security processes request before it gets to your controller in a filter configured in spring security configuration.
There is a documentation on how to configure spring security with SiteMinder.
The rules in your configuration will define the access to resources
Depends what you get in session. If somehow u can to take user and password from session you can authenticate user directly from code as :
#Autowired
AuthenticationManager authenticationManager;
...
public boolean autoLogin(String username, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication auth = authenticationManager.authenticate(token);
if (auth.isAuthenticated()) {
logger.debug("Succeed to auth user: " + username);
SecurityContextHolder.getContext().setAuthentication(auth);
return true;
}
return false;
}

Spring Security in single page app

I am new to the world of web development and my latest task requires me to use backbonesjs and requirejs on front end and spring boot on back end.I am supposed to have two pages one serving the login template and after its successful authentication I am supposed to show index.html which will show me username and password of logedin user.I am able to submitt loginform using ajax in my loginview and on its authentication I want to serve the index1.html.But when i do windows.location.href to serve index.html nothing happens.I guess spring security is redirecting to he same page again.How can I achieve that.
maybe this is help for you.
Spring 3 with No xml.
I have two pages. These are login and index jsp.
Spring WebSecurityConfiguerer configure method like this.
#Override
protected void configure( HttpSecurity http ) throws Exception{
http.exceptionHandling().
accessDeniedPage( "/login?accessDeniedError=1").and().
authorizeRequests().anyRequest().authenticated().and().
formLogin().loginPage( "/login" ).
defaultSuccessUrl( "/index", true ).
failureUrl( "/login?authenticationFailure" ).permitAll().and().
logout().deleteCookies( "JSESSIONID" ).
invalidateHttpSession( true).permitAll();
}
Spring Mvc Controller's methods is :
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login( ModelMap model, HttpServletRequest request ){
//business logic
return "login";
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index( ModelMap model, Principal principal, HttpServletRequest request ){
//business logic
return "index";
}

Resources