简体   繁体   English

在我的项目中应用 Spring 安全性后,controller 无法正常工作,每当我调用 rest 控制器时,它只响应 404 代码

[英]After Applying Spring Security in my project, controller not working, whenever i called the rest controllers, its simply response with 404 code

After Applying Spring Security in my project, controller not working, whenever I called the rest controllers, it's simply response with 404 code.在我的项目中应用 Spring 安全性后,controller 无法正常工作,每当我调用 rest 控制器时,它只是用 404 代码响应。

This is my Spring Security Configuration class这是我的 Spring 安全配置 class

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().permitAll();
    }
}

My Application.properties file我的 Application.properties 文件

spring.datasource.url = jdbc:mysql://192.168.1.62:3306/dummy_users?useSSL=false
spring.datasource.username = root
spring.datasource.password = MySQL62$$
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

spring.jpa.hibernate.ddl-auto = update

My Initial Data Loader class我的初始数据加载器 class

package com.dummy.users.auth.config;

import com.dummy.users.auth.entity.Privilege;
import com.dummy.users.auth.entity.UsersProfileEntity;
import com.dummy.users.auth.entity.UsersRoles;
import com.dummy.users.auth.repository.PrivilegeRepository;
import com.dummy.users.auth.repository.UserProfileRepository;
import com.dummy.users.auth.repository.UsersRolesRepository;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {

    boolean alreadySetup = false;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private UsersRolesRepository usersRolesRepository;

    @Autowired
    private PrivilegeRepository privilegeRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if (alreadySetup) {
            return;
        }
        Privilege readPrivilege
                = createPrivilegeIfNotFound("READ_PRIVILEGE");
        Privilege writePrivilege
                = createPrivilegeIfNotFound("WRITE_PRIVILEGE");

        List<Privilege> adminPrivileges = Arrays.asList(
                readPrivilege, writePrivilege);
        createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
        createRoleIfNotFound("ROLE_USER", Arrays.asList(readPrivilege));

//        UsersRoles adminRole = usersRolesRepository.findByName("ROLE_ADMIN");
//        UsersProfileEntity user = new UsersProfileEntity();
//        user.setFirstName("KarthickRaj");
//        user.setLastName("Rathinakumar");
//        user.setPhoneNumber("95245356782");
//        user.setPassword(passwordEncoder.encode("2342423$$#"));
//        user.setEmailId("rkarthickraj@gmail.com");
//        user.setStatus("Active");
//        user.setRoles(Arrays.asList(adminRole));
//        user.setEnabled(true);
//        userProfileRepository.save(user);
        alreadySetup = true;
    }

    @Transactional
    private Privilege createPrivilegeIfNotFound(String name) {

        Privilege privilege = privilegeRepository.findByName(name);
        if (privilege == null) {
            privilege = new Privilege();
            privilege.setName(name);
            privilegeRepository.save(privilege);
        }
        return privilege;
    }

    @Transactional
    private UsersRoles createRoleIfNotFound(
            String name, Collection<Privilege> privileges) {

        UsersRoles role = usersRolesRepository.findByName(name);
        if (role == null) {
            role = new UsersRoles();
            role.setName(name);
            role.setPrivileges(privileges);
            usersRolesRepository.save(role);
        }
        return role;
    }

}

MyApplication.class for my Application MyApplication.class 用于我的应用程序

package com.dummy.users;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class UsersApplication {

    private static final Logger LOGGER = LogManager.getLogger(UsersApplication.class.getName());

    public static void main(String[] args) {
        SpringApplication.run(UsersApplication.class, args);
    }

}

MyController class, when I access the controller it response 404 issue MyController class,当我访问 controller 它响应 404 问题

 @RestController
    public class UsersLinkAdminController {

        @GetMapping("/")
        public String getUsersStatus() {
            return "<!DOCTYPE html>\n"
                    + "<html>\n"
                    + "<head>\n"
                    + "<title>Page Title</title>\n"
                    + "<style>\n"
                    + "body {\n"
                    + "  background-color: black;\n"
                    + "  text-align: center;\n"
                    + "  color: white;\n"
                    + "  font-family: Arial, Helvetica, sans-serif;\n"
                    + "}\n"
                    + "</style>\n"
                    + "</head>\n"
                    + "<body>\n"
                    + "\n"
                    + "<h1>Welcome to Dummy Oraganization</h1>\n"
                    + "<p>Users Module Running Sucessfully</p>\n"
                    + "<p>For More Details Call Support team</p>\n"
                    + "<img src=\"avatar.png\" alt=\"Avatar\" style=\"width:200px\">\n"
                    + "\n"
                    + "</body>\n"
                    + "</html>";
        }

    }

So Anyone Please tell me about the issues.所以任何人请告诉我这些问题。

Your security configuration needs additional configuration.您的安全配置需要额外的配置。 You need an authenticationProvider example of inmemory:您需要一个 inmemory 的 authenticationProvider 示例

 @Autowired
            public void configureInMemoryAuthentication(AuthenticationManagerBuilder auth) throws Exception
            {
                auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder.encode("admin@123#")).roles("ADMIN");
            }

And DAO authenticationProvider:和 DAO authenticationProvider:

@Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(encoder());

        return authProvider;

    }

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

相关问题 将Spring Security合并到我的项目后出现404错误 - 404 error after incorporationg spring security to my project REST项目的Spring Security无法正常工作 - Spring security with REST project not working 为 REST 控制器调用两次 Spring 安全自定义过滤器 - Spring security custom filter called twice for REST Controller API端点使用Spring REST controller调用后返回404 - API endpoint using Spring REST controller returns 404 after it is invoked Spring MVC Rest Controller 404 - Spring MVC Rest Controller 404 带有REST和MongoDB的Spring项目-404页无任何工作 - Spring project with REST and MongoDB - 404 pages and nothing working Spring-MVC:Controller 在一个项目中工作,但不在另一个项目中工作(未找到 404) - Spring-MVC: Controller working in one project but not the other(404 not found) Spring Rest Controller 在执行前处理方法后没有被调用 - Spring Rest Controller not getting called after Pre Handle Method executed Spring MVC在Rest Controller上调用Web服务并返回xml响应后,如何在发送响应后执行其他功能? - Spring MVC after calling webservice at Rest Controller and returning xml response how can I execute other function after response sent? 不调用Spring REST API控制器 - Spring REST API controller is not called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM