Deploying Spring Security in ZK + Spring Framework + Hibernate: Part One

    Good day to all. As promised, I will try to highlight the topic of security in a web application written in the ZK Framework . Why is part one? Because in this article I will show you the fastest and easiest method for implementing Spring Security using the jsp page as the authorization page; in the subsequent article (s), more complex and interesting methods will be described using zul as the construction of an authorization page.
    We won’t write a web application from scratch, but take as a basis my past application, which I described in this topic .
    What we need:
    This method can also be implemented in different ways, either by storing users, their passwords and rights in the Spring Security xml configuration, or storing in a database. Since our application already works with the Oracle database, so that users would not be stored in the database. As the spring documentation tells us, during a default deployment, Spring Security looks at the database for 2 tables (users and authorities). With group policy, the presence of such tables as: groups, group_authorities, group_members is required (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
    java:comp/env/jdbc/taskdborg.hibernate.dialect.OracleDialectfalse
    				update -->



    I will dwell on some points:
    • secured-annotations="enabled" jsr250-annotations="enabled" />- gives us the opportunity to use annotations of the form @RolesAllowed ("ROLE_ADMIN") , for a group of rights, this string will look like @RolesAllowed ({"ROLE_ADMIN", "ROLE_USER"});
    • access="IS_AUTHENTICATED_ANONYMOUSLY" /> - we say that everyone can go to the login.jsp page;
    • access="ROLE_ADMIN,ROLE_USER" /> - only users who have the rights ROLE_ADMIN and / or ROLE_USER can go to all pages
    • default-target-url="/index.zul" always-use-default-target="true"
      authentication-failure-url="/login.jsp?login_error=1" />
      - with the correct login / password, go to the index.zul page (of course, if the rights of this user allow it to be done), otherwise we display an error code.

    Also do not forget to add to web.xml:
    springSecurityFilterChainorg.springframework.web.filter.DelegatingFilterProxyspringSecurityFilterChain/*

    Everything is done with the configuration. Now we will write the login.jsp login page.
    <%@ page language="java" contentType="text/html; charset=utf-8"
    	pageEncoding="utf-8"%>
    
    <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%>
    
    
    Форма Авторизации

    Авторизация

    Не правильный логин или пароль. Попробуйте заново.
    Пользователь:
    Пароль:

    You can run and look at our fruits.
    Let's play around with the differentiation of rights. For example, we allow only a user with ROLE_ADMIN privileges to delete users from the system. To do this, in the procedure ( PersonImpl ) before the procedure for deleting a user, we write the following: We also display the name of the logged in user. First, create Label components with id = "labelLogin", which will serve to display the username and Toolbarbutton, which will serve us as the user exit button. In the index.zul file before the line
    @RolesAllowed("ROLE_ADMIN")
    public boolean delete(Person pers)


    , добавим следующее:

    Ну и в классе PersonInfo внутри метода public void onCreate() реализуем возможность вывода имени пользователя:
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    ((Label) this.getFellow("labelLogin")).setValue(userDetails.getUsername());
    

    В данном коде мы получаем все данные пользователя, которые содержатся в UserDetails и компонент Label с id = «labelLogin» из формы index.zul, в который мы передадим имя пользователя.
    Теперь, запустив наше приложении, по адресу
    http://localhost:port/NameOfProject
    мы увидим, что автоматом нас перенаправили на страницу login.jsp.

    Also popular now: