powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему не работает Log Out
17 сообщений из 17, страница 1 из 1
Почему не работает Log Out
    #39825651
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
У меня админ логинится и я хочу чтобы он мог выходить из своего аккаунта
Security Config

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }

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

        http.authorizeRequests()
                .anyRequest().access("hasRole('ROLE_ADMIN')")
                .and()
                .authorizeRequests().antMatchers("/login**").permitAll()
                .and()
                .authorizeRequests().antMatchers("/allStudents**").permitAll()
                .and()
                .formLogin().loginPage("/login").loginProcessingUrl("/loginAction").permitAll()
                .and()
                .logout().logoutSuccessUrl("admin").permitAll()
                .and()
                .csrf().disable();
    }
}



admin.jsp
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Secure page</title>    
	</head>
	<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
		<h2>Welcome : ${pageContext.request.userPrincipal.name}
			| <a href="<c:url value="/logout" />" > Logout</a></h2>
	</c:if>
	</body>
</html>



login.jsp

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Custom login</title>
    	<style type="text/css">
    		.error {
    			color: #ff0000;
    			font-weight: bold;
    		}    		
    		.msg {
    			color: #008000;
    			font-weight: bold;
    		}
    	</style>
	</head>
    <body onload='document.loginForm.username.focus();'>
    <h1>Login Form</h1>

    <c:if test="${not empty errorMessge}"><div style="color:red; font-weight: bold; margin: 30px 0px;">${errorMessge}</div></c:if>

    <div id="login-box">

        <h3>Login with Username and Password</h3>

        <c:if test="${not empty error}">
            <div class="error">${error}</div>
        </c:if>
        <c:if test="${not empty msg}">
            <div class="msg">${msg}</div>
        </c:if>

        <form name="loginForm" action='<spring:url value="/loginAction"/>' method="post">
            <table>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td><button type="submit">Login</button></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
</html>



Авторизайшин контроллер
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
package adil.java.schoolmaven.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AuthorizationController {

    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public ModelAndView adminPage() {

        ModelAndView m = new ModelAndView();
        m.addObject("title", "Successfully logged in");
        m.addObject("message", "home");
        m.setViewName("admin");
        return new ModelAndView("redirect: allStudents");
    }
}



Здесь вроде ссылку правильную поставил

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
<header>
  <a href="" class="logo">Школа Программирования</a>
  <nav>
      <ul class="topmenu">
        <li><a href="">Home</a></li>
        <li><a href="" class="submenu-link">Students</a>
          <ul class="submenu">
            <li><a href="allStudents">All Students</a></li>
            <li><a href="addStudent">Add Student</a></li>
          </ul>
        </li>
        <li><a href="login">Log in</a></li>
        <li><a href="admin">Log out</a></li>
        
      </ul>
    </nav>
</header>
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825906
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019Здесь вроде ссылку правильную поставил

Код: java
1.
        <li><a href="admin">Log out</a></li>



Что по вашему тут правильного?
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825910
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

У меня же там вроде правильно, что не так? "Логин" нужно прописать?
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825912
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Если честно, то вы тут уже немного поднадоели!
Читать руководства не хотите, изучать вопрос не хотите, а хотите чтобы всё вам рассказали да сделали за вас!
Я давал ссылку, где все это описывалось. Вы читали?
Вот это видели?
Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:url value="/j_spring_security_logout" var="logoutUrl" />

		<!-- csrt support -->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" 
			name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>
	
	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
		<h2>
			Welcome : ${pageContext.request.userPrincipal.name} | <a
				href="javascript:formSubmit()"> Logout</a>
		</h2>
	</c:if>

</body>
</html>


Либо не читали, либо не поняли...
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825913
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Я читал, вот все по нему делаю. Да я же не весь код прошу написать, просто посмотреть где ошибка или поправить.
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825914
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Да возможно я надоел, просто вы же видели хоть какой то год сам пытаюсь написать, да выходит коряво и где-то ошибки. Но главное пытаюсь сам написать)
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825915
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Я вот добавил ваш код создав новую JS под названием Logout.
Я же здесь его правильно написать?
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent**").access("hasRole('ROLE_ADMIN')")
             
                
                
                .and()
                .authorizeRequests().antMatchers("/**").permitAll() 
                .and()
                .formLogin()
                .successForwardUrl("/allStudents")
                .loginPage("/allStudents")
                
                .loginProcessingUrl("/loginAction")
                .and()
                .logout().logoutSuccessUrl("/").permitAll()
                .and()
                .csrf().disable();
    }
}
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825934
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Ну неужели трудно заменить
Код: java
1.
        <a href="admin">Log out</a>



на

Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
	<c:url value="/j_spring_security_logout" var="logoutUrl" />

		<!-- csrt support -->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" 
			name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>
	
	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

			<a href="javascript:formSubmit()"> Logout</a>
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825940
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Можете посмотреть я создал JSP - Logout.jsp

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:url value="/Logout" var="logoutUrl" />

		<!-- csrt support -->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" 
			name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>
	
	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
		<h2>
			Welcome : ${pageContext.request.userPrincipal.name} | <a
				href="javascript:formSubmit()"> Logout</a>
		</h2>
	</c:if>

</body>
</html>



И в Menutemplate.jsp я его правильно же обозначил

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
<%@page contentType="text/html" pageEncoding="UTF-8" isELIgnored="false"%>
        
<header>
  <a href="" class="logo">Школа Программирования</a>
  <nav>
      <ul class="topmenu">
        <li><a href="">Home</a></li>
        <li><a href="" class="submenu-link">Students</a>
          <ul class="submenu">
            <li><a href="allStudents">All Students</a></li>
            <li><a href="addStudent">Add Student</a></li>
          </ul>
        </li>
        <li><a href="login">Log in</a></li>
        <li><a href="Logout">Log out</a></li>
        
      </ul>
    </nav>
</header>




И в секюрити конфиге

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
package adil.java.schoolmaven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent/**").access("hasRole('ROLE_ADMIN')")
                
                
                .and()
                .authorizeRequests().antMatchers("/**").permitAll() 
                .and()
                .formLogin()
                .successForwardUrl("/allStudents")
                .loginPage("/allStudents")
                
                .loginProcessingUrl("/loginAction")
                .and()
                .logout()
                .logoutUrl("/Logout") 
                .and()
                .csrf().disable();
    }
}
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825946
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Вот жеж масло масляное!
Нажать на кнопку выход, чтобы попасть на страницу с еще одной кнопкой.
А тогда где контроллер на /Logout ???
Создается впечатление что вы совсем не понимаете как всё это работает. (Это не ругань, а констатация факта)
Методом тыка и пробы пытаетесь выстроить рабочий код.
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825947
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

как будет корректно?)
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825949
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019, 21907617
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825952
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

<a href="admin">Log out</a> // этот код же у меня в шаблоне


я вставил ваш код в admin.jsp правильно же? А секюрити конфиг правильно написал?

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" session="true" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Secure page</title>    
	</head>
	<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:url value="/j_spring_security_logout" var="logoutUrl" />

		<!-- csrt support -->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" 
			name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>
	
	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

			<a href="javascript:formSubmit()"> Logout</a>
	</body>
</html>
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825954
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А попробовать?
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825965
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

У меня пишет что страница не найдена

Получается если я запихал ваш код в admin.jsp то мне нужно удалить Logout?

admin.jsp
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" session="true" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Secure page</title>    
	</head>
	<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:url value="/j_spring_security_logout" var="logoutUrl" />

		<!-- csrt support -->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" 
			name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>
	
	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

			<a href="javascript:formSubmit()"> Logout</a>
	</body>
</html>



Security Config
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
package adil.java.schoolmaven.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}1234").roles("ADMIN");
    }

   
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/allStudents**").permitAll()
                .antMatchers("/addStudent**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/editStudent/**").access("hasRole('ROLE_ADMIN')")
             
                
                
                .and()
                .authorizeRequests().antMatchers("/**").permitAll() 
                .and()
                .formLogin()
                .successForwardUrl("/allStudents")
                .loginPage("/allStudents")
                
                .loginProcessingUrl("/loginAction")
                .and()
                .logout()
                .logoutUrl("/admin") 
                .and()
                .csrf().disable();
    }
}



Код: java
1.
http://localhost:8080/SchoolMaven/Logout
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825967
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Терпение моё кончилось!
Смотрите пример и реализуйте его в своём коде.
...
Рейтинг: 0 / 0
Почему не работает Log Out
    #39825999
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Как там в песне у Слепакова. - "Запас терпения иссяк.. Устал мириться я со злом..."
...
Рейтинг: 0 / 0
17 сообщений из 17, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Почему не работает Log Out
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]