Feb 1997

Overtime and overdue


  • Home

  • Tags

  • Categories

  • Archives

  • Search

Spring Security 5: Restric Access

Posted on 2020-07-24

Create supporting controller code and view pages

  • Add a hyperlink in home page and refer to /leaders
  • Create a controller with @GetMapping("/leaders") and return to leaders.jsp
  • Create a page for leaders
  • Repeat the job for different roles, nothing special

    Update user roles

    DemoSecurityConfig.java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // add our users for in memory authentication
    UserBuilder users = User.withDefaultPasswordEncoder();

    auth.inMemoryAuthentication()
    .withUser(users.username("john").password("test123").roles("EMPLOYEE"))
    .withUser(users.username("mary").password("test123").roles("EMPLOYEE","MANAGER"))
    .withUser(users.username("susan").password("test123").roles("EMPLOYEE","ADMIN"));
    }

Restrict Access based on Roles

General syntax:

1
.antMatchers(<< add path to match on >>).hasRole(<< authorized role >>)

or

1
2
// Any role in the list, comma-delimited list. E.g. "ADMIN","DEVELOPER","VIP","PLATINUM"
.antMatchers(<< add path to match on >>).hasAnyRole(<< authorized role >>)

DemoSecurityConfig.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/leaders/**").hasRole("MANAGER")
.antMatchers("/admins/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll();
}

In this way, if a user tries to access in a page which he is not authorized to, he will be denied by “HTTP Status 403 - Forbidden”.

Spring Security 4: Acquiring User ID and Roles

Posted on 2020-07-24

Spring Security provides JSP custom tags for accessing user id and roles

Update POM file for Spring Security JSP Tag Library

pom.xml

1
2
3
4
5
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>

Add Spring Security JSP Tag Library to JSP page

home.jsp:

1
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Display User ID

home.jsp:

1
User: <security:authentication property="principal.username"/>

Display User Roles

home.jsp:

1
Role(s): <security:authentication property="principal.authorities"/>

Note: Spring Security will automatically add a prefix for the roles. For example: if the role is “EMPLOYEE”, then it will display “[ROLE_EMPLOYEE]”

Spring Security 3: Cross Site Request Forgery(CSRF)

Posted on 2020-07-24

What is CSRF?

A security attack where an evil website tricks you into executing an action on a web application that you are currently logged in.

CSRF Protection

  • To protect against CSRF attacks
  • Embed additional authentication data / token into all HTML forms
  • On subsequent requestes, web app will verify token before processing

    Spring Security’s CSRF Protection

  • CSRF prtection is enabled by default in Spring Security
  • Spring Security uses the Synchronizer Token Pattern
    • Each request includes a session cookie and randomly generated token
  • For request processing, Spring Security verifies token before processing
  • All of this is handled by Spring Security Filters

    Use Spring Security CSRF Protection

  • For form submissions use POST instead of GET
  • Include CSRF token in form submission
  • <form:form> automagically adds CSRF token

    Manually add CSRF token

    1
    2
    3
    4
    <form action="..." method="POST">
    <input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/>

Conclusion

Using SpringMVC form tage because they’ll automatically do this work

Spring Security 3: Logout

Posted on 2020-07-24

Add logout support to Spring Security Configuration.
DemoSecurityConfig.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
// logout support for default URL /logout,
// which means we don't have to write extra code in controller
.logout()
.permitAll();
}

Add a button on page.
home.jsp:

1
2
3
4
<!-- MUST USE POST -->
<form:form action="${pageContext.request.contextPath}/logout" method="post">
<input type="submit" value="Logout"/>
</form:form>

Logout Process

  • When a logout is processed, by default Spring Security will…
  • Invalidate user’s HTTP session and remove session cookies, etc
  • Send user back to your login page
  • Append a logout parameter: ?logout

Based ont the fact that a parameter will be appended in the url, we can show a notification after log out and back to the login page

1
2
3
4
5
<c:if test="${param.logout != null}">
<div class="alert alert-success col-xs-offset-1 col-xs-10">
You have been logged out.
</div>
</c:if>

Spring Security 1: First Application

Posted on 2020-07-24

DemoController:

1
2
3
4
5
6
7
8
@Controller
public class DemoController {
// This is the index of application
@GetMapping("/")
public String showHome() {
return "home";
}
}

LoginController:

1
2
3
4
5
6
7
8
9
@Controller
public class LoginController {
// Due to the DemoSecurityConfig,
// before we accessing the index page, we have to login
@GetMapping("/showMyLoginPage")
public String showMyLoginPage() {
return "fancy-login";
}
}

login.jsp:

1
2
3
4
5
<c:if test="${param.error != null}">
<div>
Invalid username and password.
</div>
</c:if>

In Spring Security system, if the log in step fails, there will be a param error in the link, like:http://localhost:8080/showMyLoginPage?error. So jstl can be used to check if the log in fails and show different pages.

Spring Security 0: Set up

Posted on 2020-07-24

Dependencies

pom.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!-- There may be problems or bugs because of the incompatibility 
between springframework and springsecurity. Here provided an
compatible solution of versions -->
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>

<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>

<!-- Spring Security -->

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

</dependencies>

Configuration

Here we are using pure Java to do the configuration(no xml).

DemoAppConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xliu.springsecurity.demo")
public class DemoAppConfig {

// define a bean for ViewResolver
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");

return viewResolver;
}
}

MySpringMvcDispatcherServletInitializer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MySpringMvcDispatcherServeletInitializer 
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
// No root config classes for our project, only servlet config classes
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}

DemoSecurityConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// add our users for in memory authentication
UserBuilder users = User.withDefaultPasswordEncoder();
// users are loaded in memory, this is just for academic purpose, usually we will use JDBC
auth.inMemoryAuthentication()
.withUser(users.username("john").password("test123").roles("EMPLOYEE"))
.withUser(users.username("mary").password("test123").roles("EMPLOYEE","MANAGER"))
.withUser(users.username("susan").password("test123").roles("EMPLOYEE","ADMIN"));
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
// Spring Security has its own default loging page, but here we refer to a customized page
.loginPage("/showMyLoginPage")
// authendicateTheUser is done by Spring Security automatically
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll();
}
}

Bit Manipulation

Posted on 2020-07-07 Edited on 2020-07-09

Operator

&

& 1 0
1 1 0
0 0 0

|

\ 1 0
1 1 1
0 1 0

^

^ 1 0
1 0 1
0 1 0

~

~ 1 0 0 1 1
=> 0 1 1 0 0

<<

1
2
3
4
5
int a = 8;
a << 3;

before:0000 0000 0000 0000 0000 0000 0000 1000
after:0000 0000 0000 0000 0000 0000 0100 0000

>>

1
2
3
4
5
6
7
8
9
unsigned int a = 8;
a >> 3;
before:0000 0000 0000 0000 0000 0000 0000 1000
after:0000 0000 0000 0000 0000 0000 0000 0001
​
int a = -8;
a >> 3;
before:1111 1111 1111 1111 1111 1111 1111 1000
after:1111 1111 1111 1111 1111 1111 1111 1111

Common Problem

  1. Implement division

    1
    2
    3
    int a = 2;
    a >> 1; ---> 1
    a << 1; ---> 4
  2. Swap two digits

    1
    2
    3
    4
    5
    void swap(int &a, int &b) {
    a ^= b;
    b ^= a;
    a ^= b;
    }

    Explaination:
    Step 1:a ^= b —-> a = (a^b);

    Step 2:b ^= a —-> b = b\^(a^b) —-> b = (b\^b)^a = a

    Step 3:a ^= b —-> a = (a\^b)^a = (a\^a)^b = b

  3. Odd or Even
    If the last digit is 0, then even. Otherwise, odd

    1
    2
    3
    if(0 == (a & 1)) {
    even
    }
  4. Change the sign

    1
    2
    3
    int reversal(int a) {
    return ~a + 1;
    }
  5. Detect opposite sign

    1
    2
    3
    4
    int oppositeSigns(int x, int y) {
    // -1 if opposite, 0 if not
    return ((x ^ y) >> 31);
    }
    1
    2
    3
    4
    int oppositeSigns(int x, int y) {
    // 1 if opposite, 0 if not
    return ((x ^ y) >>> 31);
    }

Spring: Factory Pattern

Posted on 2020-06-27

Simple factory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {
private static Properties env = new Properties();

static{
try {
//Step 1: get IO Stream
InputStream inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
//Step 2: load() method reads a property list (key and element pairs) from the input byte stream.
env.load(inputStream);
//Stream source doesn't belong to JVM, so it can't be handled by GC and needs to be closed mannualy
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/*
Way to initial an object:
1. Constructor: UserService userService = new UserServiceImpl();
2. Refelction: This method can loose coupling
Class clazz = Class.forName("com.baizhiedu.basic.UserServiceImpl");
UserService userService = (UserService)clazz.newInstance();
*/

public static UserService getUserService() {
UserService userService = null;
try {
Class clazz = Class.forName(env.getProperty("userService"));
userService = (UserService) clazz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return userService;
}

public static UserDAO getUserDAO(){
UserDAO userDAO = null;
try {
Class clazz = Class.forName(env.getProperty("userDAO"));
userDAO = (UserDAO) clazz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return userDAO;
}

}

applicationContext.properties:

1
2
3
4
5
6
7
# Properties extends Hashtable<Object,Object>
# Map: key=String value=String
# Properties [userService = com.baizhiedu.xxx.UserServiceImpl]
# Properties.getProperty("userService")

userService = com.baizhiedu.basic.UserServiceImpl
userDAO = com.baizhiedu.basic.UserDAOImpl

General factory

There are lots of redundancy in simple factory like those exceptions in try-catch. Here introduced general factory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {
private static Properties env = new Properties();
static{
try {

InputStream inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
env.load(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getBean(String key){
Object ret = null;
try {
Class clazz = Class.forName(env.getProperty(key));
ret = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}

}

General factory shares the same applicationContext.properties with simple factory.

How to use general factory:

  1. Define class
  2. Inform the factory using applicationContext.properties
  3. Get object using BeanFactroy:
    1
    Object ret = BeanFactory.getBean("key");

Java:GET还是POST

Posted on 2020-05-30

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。

然而,在以下情况中,请使用 POST 请求:

  • 无法使用缓存文件(更新服务器上的文件或数据库)
  • 向服务器发送大量数据(POST 没有数据量限制)
  • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

Java:封装

Posted on 2020-05-26

Q. What is the difference between abstraction and encapsulation?

  • Abstraction solves the problem at design level while Encapsulation solves it implementation level.
  • In Java, Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.
  • Abstraction is about hiding unwanted details while giving out most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect inner working of an object from outside world.
AbstractionEncapsulation
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Encapsulation is a process of wrapping code and data together into a single unit
Abstraction lets you focus on what the object does instead of how it does it. Encapsulation provides you the control over the data and keeping it safe from outside misuse.
Abstraction solves the problem in the Design Level. Encapsulation solves the problem in the Implementation Level.
Abstraction is implemented by using Interfaces and Abstract Classes. Encapsulation is implemented by using Access Modifiers (private, default, protected, public)
Abstraction means hiding implementation complexities by using interfaces and abstract class. Encapsulation means hiding data by using setters and getters.
↥ back to top

Q. How Encapsulation concept implemented in JAVA?

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class EncapClass {
private String name;

public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}

public class MainClass {

public static void main(String args[]) {
EncapClass obj = new EncapClass();
obj.setName("Pradeep Kumar");
System.out.print("Name : " + obj.getName());
}
}

↥ back to top
1234…12
Feb 1997

Feb 1997

112 posts
4 categories
24 tags
© 2020 Feb 1997