Spring Security in single page app - spring

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";
}

Related

Hystrix fallback method for redirect from controller

I have a controller from which there is redirection to multiple other services. I was thinking of using hystrix fallback to redirect to a service not running page in case the service being redirected to is not running. But somehow the fallback is not working.
I have added #EnableCircuitBreaker to the main class. And using circuit breaker in my controller as below.
#HystrixCommand(fallbackMethod = "serviceNotRunning")
public ModelAndView jbotMS(final ModelMap modelMap, final HttpServletResponse response) throws JSONException {
return new ModelAndView(ParentConstants.REDIRECT + this.jbotxMicroServices +"/");
}
fallback method :
public ModelAndView serviceNotRunning(final ModelMap modelMap, final HttpServletResponse response)
{
System.out.println("Fallback called");
return new ModelAndView(Constants.LOGIN_PATH);
}
But somehow it is not working and each time I am getting the unable to connect page.
Is it not possible to use fallback on redirect or controller?

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);
}

How do I get the right user principal with Spring-Boot and Oauth2?

I am practising Spring-Boot 2.2 + Spring Security 5 + Oauth2. Following a lot of examples I am hitting a wall here.
My spring security configuration is this:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/css/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and().oauth2Login().userInfoEndpoint()
.userService(new DefaultOAuth2UserService());
}
and I have a controller with this method:
#GetMapping("/create")
public ModelAndView create(Principal principal) {
log.debug(principal);
return new ModelAndView("create.html", "topicForm", new TopicForm());
}
in the Thymeleaf template I would call <span sec:authentication="name">User</span>, and it only returns a number.
in debug, authentication is org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken, and the Principal is a DefaultOidcUser, the name attribute is "sub", which is not a name but a number in google's oauth response.
DefaultOAuth2UserService is never called before my breakpoint hits in the controller.
Where did I take the wrong turn?
--edit--
In further debugging, I think the problem stems from OAuth2LoginAuthenticationFilter calling org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService which would be configurable by oidcUserService(oidcUserService())
To get current principal you can use #AuthenticationPrincipal annotation which resolves Authentication.getPrincipal() so you can add it as argument.
public ModelAndView create(#AuthenticationPrincipal Principal principal) {
log.debug(principal);
return new ModelAndView("create.html", "topicForm", new TopicForm());
}
You can make use of the SecurityContextHolder.
public ModelAndView create() {
Object principal = SecurityContextHolder.getContext().getAuthentcation().getPrincipal();
log.debug(principal);
return new ModelAndView("create.html", "topicForm", new TopicForm());
}

How to have sessions in http basic authentication in a spring based server

I am trying to create a Spring server for an android client and am using basic authentication. I have a controller as follows:
#RequestMapping(value = "login", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody Message login(HttpSession session) {
logger.info("Accessing protected resource sid:"+session.getId());
return new Message(100, "Congratulations!", "You have logged in.");
}
#RequestMapping(value = "play", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody Message play(HttpSession session) {
logger.info("Accessing protected play resource");
return new Message(100, "Congratulations!", "Launching play.");
}
Once the client has authenticated, during login, I don't want it to need to reauthenticate while calling play.
My security config is:
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/signup","/about").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
// #formatter:on
}
}
I have tried to enable sessions above but if I try to print the session id in the request handlers in login and play, I get different ids after logging in with authentication. I am using HttpBasic security. Is it possible to have sessions in HttpBasic security? I read some articles which seemed to indicate that it is stateless and one cannot. Is there a workaround or do I have to switch to a different security model?
Client code:
On the client side, I send requests as follows for login.
#Override
protected Message doInBackground(Void... params) {
//final String url = getString(R.string.base_uri) + "/getmessage";
final String url = "http://10.0.2.2:8080/login";
// Populate the HTTP Basic Authentitcation header with the username and password
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
try { // Make the network request
Log.d(TAG, url);
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class);
if(response.getBody().getId() == 100)
login_success = true;
return response.getBody();
I am trying to write the client code for 'play' similarly but without the need to pass the authentication header. I feel, I should somehow pass a session related parameter in the request header to notify the server that it is part of the same session but cant figure out how to do that.
You are trying to archive stateful communication with sessions, but it won't work since RestTemplate is working in a stateless manner. It will not keep the state (i.e. the session id) from the login to the next call. Only by setting a custom ClientHttpRequestFactory I could see this work (I'm not sure on Android).
If you want communication with state, you could look at Apache HttpClient. By using it with a HttpContext that you re-use between requests, it will keep the state.
There is a possibility to fiddle with the session id yourself, but I can't recommend it.

Getting Basic Authentication Headers Springboot

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
}

Resources