Friday, 20 September 2019

springboot secrity


  1. very simple: add "spring-boot-starter-security" into your pom, then your app (web, api ) has security setup, and if you access the web/api , the app will show you a login page.  the default username and paswword are printed on your springboot console when it starts. they are random (password is random)
  2. if you want to change this default user and passoword, then just add below into your properties:
      , then you have username=password=admin  (note:  one of above link is wrong, these new properties need to start with
  3. more control?  e.g. roles? then as links above , just implement WebSecurityConfigurerAdapter, and you can create your users in memory with roles hardcoded.
  4. you can put your users into database as well just use JDBC with one line of code (detail, please check above links)
  5. you can setup auth2 which use tokens, similarly, it will print out a default user key.. then users can use the key to request a token.

If you want to implement  WebSecurityConfigurerAdapter  (e.g. you don't want to add security for your swagger ) .

1 thing you need to pay attention in below code, which is the password encoder, i don't know why if i don't override it , spring will throw error. but it is good to have it , because you should not persist (in my case is in memory) with plan text.  and after you added a encoder, then your password must be encoded by it.      which means,

user input the plan text password,
and then the system will encode it with your encoder/
then the system will compare the encoded the password with the password it has (in memory or database.....)  which means you need to make sure the system has an encoded password.

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private String defaultUser;
private String defaultPassword;
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
auth.inMemoryAuthentication().withUser(defaultUser).password(encoder.encode(defaultPassword)).roles("USER", "ADMIN");

protected void configure(HttpSecurity http) throws Exception {

public void configure(WebSecurity web) throws Exception {

public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);



How to call your api with basic auth:
with basic auth, your api should be able to be accessed via a url:


but this not always work. the best way is put username and password into header:

key: Authorization
value: Basic YWRtaW46YWRtaW4=

YWRtaW46YWRtaW4= is    admin:admin in base64 format.

you can get that with mac:

echo -n 'admin:admin' | openssl base64

No comments:

Post a comment