📜 ⬆️ ⬇️

Embedding Spring Security in the ZK + Spring Framework + Hibernate: Part One

Good day to all. As promised, I will try to cover the topic of security in a web application written in the ZK Framework . Why part one? Because in this article I will show you the quickest and easiest method of implementing Spring Security using the jsp page as the authorization page; the subsequent article (s) will describe more complex and interesting methods using zul as the construction of the authorization page.
We will not write a web application from scratch, but we will take as a basis my past application, which I described in this topic .
What we need:
This method can also be implemented differently, or you can store users, their passwords and rights in the xml configuration of Spring Security, or store them in a database. Since our application already works with the Oracle database, so why not store users in the database. As the spring documentation tells us, with the default deployment, Spring Security looks at the base on 2 tables (users and authorities). When group policy is required, the presence of more such tables as: groups, group_authorities, group_members (table scripts can be taken from here ).

So we create in the database 2 tables of the form:

CREATE TABLE users ( username varchar2 (50) NOT NULL PRIMARY KEY, password varchar2 (50) NOT NULL, enabled number NOT NULL ); 



 CREATE TABLE authorities ( username varchar2 (50) NOT NULL, authority varchar2 (50) NOT NULL, CONSTRAINT fk_authorities_users FOREIGN KEY (username) REFERENCES users (username) ); CREATE UNIQUE INDEX ix_auth_username ON authorities (username, authority); 

The next step is to configure our Spring Security. In the spring-config.xml file make the following changes
 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com.sample" /> <tx:annotation-driven transaction-manager="txManager" /> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/taskdb</value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="dataSource" ref="dataSource" /> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> <prop key="hibernate.show_sql">false</prop> <!--<prop key="hibernate.hbm2ddl.auto">update</prop> --> </props> </property> <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" /> <property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" /> </bean> <!-- Configure the Spring Security --> <security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" /> 


  <security:http auto-config="true"> <!-- Don't set any role restrictions on login.jsp --> <security:intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <!-- Restrict access to ALL other pages --> <security:intercept-url pattern="/**" access="ROLE_ADMIN,ROLE_USER" /> <security:form-login login-page="/login.jsp" default-target-url="/index.zul" always-use-default-target="true" authentication-failure-url="/login.jsp?login_error=1" /> <security:logout logout-url="/j_spring_security_logout" invalidate-session="true" logout-success-url="/logoutSuccess.jsp" /> </security:http> <!-- Configure the authentication provider --> <security:authentication-manager> <security:authentication-provider> <security:jdbc-user-service data-source-ref="dataSource" /> </security:authentication-provider> </security:authentication-manager> </beans> 

I will dwell on some points:

Also do not forget to add to web.xml:
  <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Everything is finished with the configuration. Now we will write the login.jsp authorization page.
 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%> <html> <head> <title> </title> <style type="text/css"> body { background: #63bad8 50% 0px repeat-x; text-align: center; } div.main { margin: 50px auto; padding: 0 0 0 0; width: 340px; border-color: black; } </style> </head> <body> <div class="main"> <h1 style="background-color: #3F3F3F; color: white; padding: 0px; margin: 0px;"></h1> <div style="background: white; border: black; padding: 0px; margin: 0px;" align="center" dir="ltr"> <c:if test="${not empty param.login_error}"> <font color="red">     .  .</font> </c:if> <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST" style="background: white;"> <table> <tr> <td style="font-style: oblique">:</td> <td><input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' /> </td> </tr> <tr> <td style="font-style: oblique">:</td> <td><input type='password' name='j_password'> </td> </tr> <tr align="center"> <td colspan='2' align="center"><input name="submit" value="" type="submit"> <input name="reset" value="" type="reset"> </td> </tr> </table> </form> </div> </div> </body> </html> 

You can run and look at our fruits.
Let's play now with the division of rights. For example, allow only a user with ROLE_ADMIN rights to delete users from the system. To do this, in the procedure ( PersonImpl ) before the procedure for deleting a user, we will write the following:
@RolesAllowed("ROLE_ADMIN")
public boolean delete(Person pers)

Also display the name of the logged in user.
To begin with, we will create Label components with id = “labelLogin”, which will serve to display the user name and Toolbarbutton, which will serve us with the user exit button. In the index.zul file before the line <listbox id="lbPerson" hflex="1" vflex="1" checkmark="true" , add the following:
  <toolbar> <label id="labelLogin"/> / <toolbarbutton label="" href="/j_spring_security_logout"/> </toolbar> 

Well, in the PersonInfo class inside the public void onCreate () method, we implement the ability to display the user name:
 UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); ((Label) this.getFellow("labelLogin")).setValue(userDetails.getUsername()); 

In this code, we get all user data that is contained in UserDetails and the Label component with id = "labelLogin" from the index.zul form, into which we will pass the user name.
Now, by running our application, at
 http://localhost:port/NameOfProject 
we will see that we were automatically redirected to the login.jsp page.

')

Source: https://habr.com/ru/post/129392/


All Articles