Java 实现Spring Security的自定义UserDetailService

Java 实现Spring Security的自定义UserDetailService,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我是spring的新手,我想实现spring security的自定义UserDetailService,但我的应用程序的身份验证是由Legacy完成的,它公开了一个Web服务,该服务接受用户ID、密码、酒店代码和用户类型。 我创建了一个自定义身份验证提供程序,它接受用户ID、密码、酒店代码和用户类型。我没有创建/定义任何userdetailsservice,因为我不能拥有loadByUsername等,因为只有该服务才能进行身份验证 这是我创建的数据库 如果存在rsosdb,则删除数据库 CR

我是spring的新手,我想实现spring security的自定义UserDetailService,但我的应用程序的身份验证是由Legacy完成的,它公开了一个Web服务,该服务接受用户ID、密码、酒店代码和用户类型。 我创建了一个自定义身份验证提供程序,它接受用户ID、密码、酒店代码和用户类型。我没有创建/定义任何userdetailsservice,因为我不能拥有loadByUsername等,因为只有该服务才能进行身份验证

这是我创建的数据库 如果存在rsosdb,则删除数据库

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>
/** 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;
LoginServiceImpl,它从扩展了UserDetailService的LogicService实现

@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";
    }
}
这是我的spring安全配置类

@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);
    }

此配置未使用spring security来控制访问。。每次尝试登录时。loadUserByUsername,然后允许您访问,因为您尚未在loadUserByUsernameSo中执行实际身份验证,我如何将其配置为与spring安全性一起使用?请帮助,我现在没主意了。仍然不起作用,当我尝试在没有登录的情况下访问/Admin时,它没有将我重定向到403,而是给了我状态500和空指针异常。
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(service);
    }