Created
April 16, 2018 01:06
-
-
Save TwiN/19f1c9e911af5837f5f53a8398c9df37 to your computer and use it in GitHub Desktop.
Spring Security with inMemoryAuthentication + passwordEncoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
@RestController | |
public class ExampleController { | |
@GetMapping("/") | |
public Object index() { | |
return getCurrentUser(); | |
} | |
public Object getCurrentUser() { | |
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
return auth.getPrincipal(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | |
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | |
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | |
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | |
import org.springframework.security.crypto.password.PasswordEncoder; | |
@Configuration | |
@EnableWebSecurity | |
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { | |
// secret123 | |
private static final String ENCODED_PASSWORD = "$2a$10$AIUufK8g6EFhBcumRRV2L.AQNz3Bjp7oDQVFiO5JJMBFZQ6x2/R/2"; | |
@Override | |
protected void configure(HttpSecurity http) throws Exception { | |
http | |
.csrf().disable() | |
.authorizeRequests() | |
.anyRequest().authenticated() | |
.and().formLogin().permitAll() | |
.and().logout().permitAll(); | |
} | |
@Override | |
protected void configure(AuthenticationManagerBuilder auth) throws Exception { | |
auth.inMemoryAuthentication() | |
.passwordEncoder(passwordEncoder()) | |
.withUser("user") | |
.password(ENCODED_PASSWORD) | |
.roles("USER"); | |
} | |
@Bean | |
public PasswordEncoder passwordEncoder() { | |
return new BCryptPasswordEncoder(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment