BAEL-1428: Adding example for manually set authenticated user (#3423)

This commit is contained in:
Antonio David Perez Morales 2018-01-15 21:00:21 +01:00 committed by Grzegorz Piwowarek
parent 7e5940b578
commit 293968321e
4 changed files with 186 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package org.baeldung.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = "/custom")
public class LoginController {
@Autowired
private AuthenticationManager authManager;
public LoginController() {
super();
}
// API
// custom login
@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(@RequestParam("username") final String username, @RequestParam("password") final String password, final HttpServletRequest request) {
UsernamePasswordAuthenticationToken authReq =
new UsernamePasswordAuthenticationToken(username, password);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", sc);
}
}

View File

@ -0,0 +1,27 @@
package org.baeldung.web.controller;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "/custom")
public class PrintUserController {
public PrintUserController() {
super();
}
// API
// print user
@RequestMapping(value = "/print", method = RequestMethod.GET)
public void printUser() {
SecurityContext sc = SecurityContextHolder.getContext();
System.out.println("Logged User: "+sc.getAuthentication().getName());
}
}

View File

@ -0,0 +1,58 @@
package org.baeldung.security.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ManualSecurityConfig extends WebSecurityConfigurerAdapter {
public ManualSecurityConfig() {
super();
}
// java config
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER").and().withUser("admin").password("adminPass").authorities("ROLE_ADMIN");
}
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.mvcMatchers("/custom/login").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.headers().cacheControl().disable()
.and()
.csrf().disable()
;
// @formatter:on
}
}

View File

@ -0,0 +1,58 @@
package org.baeldung.security.spring;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.http.HttpSession;
import org.baeldung.spring.MvcConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MvcConfig.class, ManualSecurityConfig.class })
public class ManualSecurityIntegrationTest {
@Autowired
WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(SecurityMockMvcConfigurers.springSecurity()).build();
}
/**
* Execute custom login and access the endpoint
*/
@Test
public void whenLoginIsSuccessFulThenEndpointCanBeAccessedAndCurrentUserPrinted() throws Exception {
mockMvc.perform(get("/custom/print"))
.andExpect(status().isUnauthorized());
HttpSession session = mockMvc.perform(post("/custom/login").param("username", "user1").param("password", "user1Pass"))
.andExpect(status().isOk())
.andReturn()
.getRequest()
.getSession();
mockMvc.perform(get("/custom/print").session((MockHttpSession) session))
.andExpect(status().is2xxSuccessful());
}
}