繁体   English   中英

实现Spring Security的Custom UserDetailService

[英]Implement Custom UserDetailService of Spring Security

我是Spring的新手,我想实现Spring安全性的自定义UserDetailService,但是对我的应用程序的身份验证是由Legacy完成的,该遗产公开了一个使用userid,password,hotel_code和user_type的Web服务。 我创建了一个自定义身份验证提供程序,其中包含用户ID,密码,hotel_code和user_type。 我没有创建/定义任何userdetailsservice,因为我没有loadByUsername等,因为该服务仅执行身份验证。

这是我在存在rsosdb时创建DROP DATABASE的数据库;

CREATE DATABASE rsosdb;

use rsosdb;

-- Create Administrator user and grant privileges
Drop procedure if exists drop_user_if_exists;
DELIMITER //

CREATE PROCEDURE drop_user_if_exists()
BEGIN
    DECLARE userCount BIGINT DEFAULT 0 ;

    SELECT COUNT(*) INTO userCount FROM mysql.user
    WHERE User = 'admin' and  Host = 'localhost';

    IF userCount > 0 THEN
        DROP USER admin@localhost;
    END IF;
END ; //
DELIMITER ;

CALL drop_user_if_exists() ;

CREATE USER admin@localhost IDENTIFIED BY 'gfam';

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP
ON rsosdb.*
TO admin@localhost;


-- Create T_Env table
CREATE TABLE T_Env (
hotel_code tinyint(4),
hotel_name varchar(50) NOT NULL,
logo_img mediumblob NOT NULL,
password varchar(30) NOT NULL,
order_start time NOT NULL,
order_end time NOT NULL,
currency varchar(4), 
regist_date datetime,
update_date datetime,
del_flag tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (hotel_code)
);

-- Create T_Delivery  Table
CREATE TABLE T_Delivery(
hotel_code tinyint(4),
delivery_code tinyint(4) auto_increment,
delivery_name varchar(50),
regist_date datetime,
update_date datetime,
del_flag tinyint(4) DEFAULT '0',
FOREIGN KEY (hotel_code) 
REFERENCES T_Env(hotel_code),
PRIMARY KEY (delivery_code, hotel_code)
);

-- Create T_Category Table
CREATE TABLE T_Category(
hotel_code tinyint(4),
category_code tinyint(4) auto_increment,
category_name varchar(20) NOT NULL,
img_file mediumblob,
regist_date datetime,
update_date datetime,
version tinyint(4) DEFAULT '1',
del_flag tinyint(4) DEFAULT '0',
PRIMARY KEY (category_code, hotel_code),
FOREIGN KEY (hotel_code) 
REFERENCES T_Env(hotel_code)
);

-- Create T_Items Table
CREATE TABLE T_Items(
hotel_code tinyint(4),
item_code tinyint(6) auto_increment,
category_code tinyint(4) NOT NULL,
item_name varchar(50) NOT NULL,
price decimal NOT NULL,
item_summary varchar(50) NOT NULL,
item_detail text NOT NULL,
img_file mediumblob NOT NULL,
order_limit int NOT NULL,
order_stop tinyint(1) NOT NULL DEFAULT '0',
regist_date datetime,
update_date datetime,
version tinyint(4) DEFAULT '1',
del_flag tinyint(4) DEFAULT '0',

FOREIGN KEY (hotel_code) 
REFERENCES T_Env(hotel_code),
FOREIGN KEY (category_code)
REFERENCES  T_Category(category_code),
PRIMARY KEY (item_code, hotel_code)
);

-- Create T_Order table
CREATE TABLE T_Order(
hotel_code tinyint(4),
order_code int(10) auto_increment,
room_number tinyint(4),
delivery_code tinyint(4),
order_date datetime,
delivery_date datetime,
response_person varchar(50), 
order_person varchar(50),
status tinyint(4)  DEFAULT '0',
regist_date datetime,
update_date datetime,
version tinyint(4) DEFAULT '1',
asap tinyint(4) ,
del_flag tinyint(4) DEFAULT '0',
FOREIGN KEY (hotel_code) 
REFERENCES T_Env(hotel_code),
FOREIGN KEY (delivery_code)
REFERENCES  T_Delivery(delivery_code),
PRIMARY KEY (order_code, hotel_code)
);

-- Create T_Concierge table
CREATE TABLE  T_Concierge(
hotel_code tinyint(4),
concierge_code varchar(4),
concierge_name varchar(30),
password varchar(30) NOT NULL,
regist_date datetime,
update_date datetime,
version tinyint(4) DEFAULT '1',
del_flag tinyint(4) DEFAULT '0',
PRIMARY KEY (concierge_code, hotel_code)
);

-- Create T_OrderItem Table
CREATE TABLE T_OrderItem(
hotel_code tinyint(4),
order_code int(10),
item_code tinyint(6),
amount tinyint(4) DEFAULT '0',
price decimal NOT NULL,
status tinyint(4) DEFAULT '0',
delivery_person varchar(25),
delivery_time datetime,
del_flag tinyint(4) DEFAULT '0',

FOREIGN KEY (hotel_code) 
REFERENCES T_Env(hotel_code),

FOREIGN KEY (order_code)
REFERENCES  T_Order(order_code),

FOREIGN KEY (item_code)
REFERENCES  T_Items(item_code),

PRIMARY KEY (hotel_code, order_code, item_code)
);

这是mybatis

酒店礼宾部

<select id="selectOne" parameterType="map" resultType="kh.com.gfam.rsos.common.entity.HotelConciergeEntity">
    SELECT 
        hotel_code,
        concierge_code,
        concierge_name,
        password,
        regist_date,
        update_date,
        version,
        del_flag
    FROM
        t_concierge
    WHERE
        hotel_code = #{hotel_code} 
    AND
        concierge_code = #{concierge_code}
    AND
        del_flag = 0           
</select>

酒店环境

<select id="selectOne" parameterType="java.lang.Integer" resultType="kh.com.gfam.rsos.common.entity.HotelEnvironmentEntity">

    SELECT 
        hotel_code,
        hotel_name,
        logo_img,
        password,
        order_start,
        order_end,
        currency,
        regist_date,
        update_date,
        del_flag
    FROM
        t_env
    WHERE
        hotel_code = #{hotel_code} 
    AND
        del_flag = 0     
</select>

这是DTO课程

 /** Hotel Code */
 private int hotel_code;
 /** Concierge Code */
 @Size(min = 1, max = 4)
 @NotNull
 @Pattern(regexp = "0-9")
 private String concierge_code;
 /** Concierge Name */
 @Size(min = 1, max = 30)
 @Pattern(regexp = "[A-Za-z]")
 private String concierge_name;
 /** Password */
 @Size(min = 8, max = 30)
 @NotNull
 private String password;
 /** Delete Flag */
 private int delete_flag;
 /** Register Date */
 private Date regist_date;
 /** Update Date */
 private Date update_date;

环境

/** Hotel Code */
private int hotel_code;
/** Hotel Name */
@Size(min = 1, max = 50)
@NotNull
@Pattern(regexp = "[A-Za-z]")
private String hotel_name;
/** Image File */
@NotNull
private byte[] logo_img;
/** Password */
@Size(min = 8, max = 30)
@NotNull
private String password;
/** Order Start Time */
@NotNull
@DateTimeFormat(pattern = "HH:mm:ss")
@Column(name="order_start")
private Date order_start;
/** Order Stop Time */
@NotNull
@Future
@Column(name="order_end")
@DateTimeFormat(pattern = "HH:mm:ss")
private Date order_end;
/** Currency */
@Size(min = 3, max = 4)
@NotNull
@Pattern(regexp = "[A-Za-z]")
private String currency;
/** Register Date */
private Date regist_date;
/** Update Date */
private Date update_date;
/** Delete Flag */
private int del_flag;

从LogicService实现的LoginServiceImpl扩展了UserDetailService

@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    private HotelConciergeDAO conciergeDao;

    @Autowired
    private HotelEnvironmentDAO environentDao;

    @Override
    public UserDTO authenicate(int hotel_code, String user_id, String password, int user_type)
            throws ApplicationException {

        if (user_type == 1) {
            HotelConciergeEntity entity = conciergeDao.selectOne(hotel_code, user_id);
            if (entity == null) {
                throw new ApplicationException("12345");
            } else if (!password.equals(entity.getPassword())) {
                throw new ApplicationException("12345");
            }
            UserDTO dto = new UserDTO();
            dto.setHotel_code(hotel_code);
            dto.setUser_id(user_id);
            dto.setUser_name(entity.getConcierge_name());
            dto.setPassword(password);
            dto.setUser_type(user_type);
            return dto;
        } else {
            HotelEnvironmentEntity entity = environentDao.selectOne(hotel_code);
            if (entity == null) {
                throw new ApplicationException("12345");
            } else if (!password.equals(entity.getPassword())) {
                throw new ApplicationException("12345");
            }
            UserDTO dto = new UserDTO();
            dto.setHotel_code(hotel_code);
            dto.setUser_name("Admin");
            dto.setPassword(password);
            dto.setUser_type(user_type);
            return dto;
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new User(username,"",true,true,true,true,AuthorityUtils.NO_AUTHORITIES);
    }
}

这是控制器类

@RequestMapping(value = "/Login", method = RequestMethod.POST)
public String authenicate(UserDTO dto, Model model, HttpSession session) {
    logger.info("User is attemp to loggin");;
    int hotel_code = dto.getHotel_code();
    String user_id = dto.getUser_id();
    String password = dto.getPassword();
    int user_type = dto.getUser_type();
    UserDTO userData = null;
    try {
        userData = login.authenicate(hotel_code, user_id, password, user_type);
    } catch (ApplicationException e) {
        e.printStackTrace();
    }
    model.addAttribute("userData", userData);
    session.setAttribute("userData", userData);
    if (userData.getUser_type() == 1) {
        return "redirect:New_Arrival";
    } else {
        return "redirect:Admin/Main_Info";
    }
}

这是我的春季安全配置类

@Configuration
@ComponentScan("kh.com.gfam.rsos.common.config")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginService service;

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

        http.authorizeRequests().antMatchers("/Admin/**", "/Concierge/**")
                .access("isAuthenticated()").and().formLogin()
                .loginPage("/Login").failureUrl("/Login?error")
                .and().logout().logoutSuccessUrl("/Login?logout")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/403")
                .and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
    }
}

这是登录视图 在此处输入图片说明

我根本无法使用它,有人可以指出错误或告诉我是否可能吗?

谢谢。

将此添加到Spring安全配置类。

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(service);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM