CRUB,前端身份验证问题,春季安全性

时间:2020-07-07 18:50:42

标签: java reactjs spring spring-boot spring-security

4天,我找不到任何解决方案。我在弹簧靴上有后端,在React上有前端。如何在前端页面上进行登录系统和会话?我有2个RestControllers进行测试。

=== MimeHeaders ===
host = localhost:8081
connection = keep-alive
content-length = 53
cache-control = max-age=0
upgrade-insecure-requests = 1
origin = http://localhost:8081
content-type = application/x-www-form-urlencoded
user-agent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
accept = text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site = same-origin
sec-fetch-mode = navigate
sec-fetch-user = ?1
sec-fetch-dest = document
referer = http://localhost:8081/loginPage
accept-encoding = gzip, deflate, br
accept-language = en-US,en;q=0.9
cookie = ztcookcsr=e74ce2f0-b7d7-4f09-a1a7-0834c599e32d; Idea-7029dd45=276a767c-c715-4838-9756-45bea2bdafcc; Idea-407559eb=da31aa72-ff54-488a-b154-e909efb275c3

在服务器站点“ localhost:8080 / protected and / public”上,一切正常,当我未通过身份验证时返回登录表单,然后我可以使用凭据登录。我如何在我的自定义首页上完全相同?我只能通过以下方式显示我的公开页面:

@GetMapping("/protected")
    public String showProtected() {
        return "protected page";
    }

    @GetMapping("/public")
    public String showPublic(){
        return "public page";
    }

如何在前端页面上使用自定义登录表单进行登录会话以获取受保护的页面?这是我的安全配置:

axios.get("http://localhost:8080/account/public")
            .then(response => this.setState({stuff: response.data}))

1 个答案:

答案 0 :(得分:0)

您的/ account / protected受用户hase角色USER保护。 因此,您应该将身份验证过程返回的令牌发送出去,以保护溃败

axios.get('http://localhost:8080/protected', {
            headers: {
                'authorization': localStorage.getItem('token'),
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }).then(res => {
            resolve(res);
        }).catch(error => {
            reject(error.message);
        });

我希望它对您有用,祝您好运